Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/CR-1799- Create FTP connection and upload file to FTP directory #75

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions ftp_file_upload/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.testsigma.addons</groupId>
<artifactId>ftp_file_upload</artifactId>
<version>1.0.1</version>
<packaging>jar</packaging>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<testsigma.sdk.version>1.2.13_cloud</testsigma.sdk.version>
<junit.jupiter.version>5.8.0-M1</junit.jupiter.version>
<testsigma.addon.maven.plugin>1.0.0</testsigma.addon.maven.plugin>
<maven.source.plugin.version>3.2.1</maven.source.plugin.version>
<lombok.version>1.18.20</lombok.version>

</properties>

<dependencies>
<dependency>
<groupId>com.testsigma</groupId>
<artifactId>testsigma-java-sdk</artifactId>
<version>${testsigma.sdk.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.14.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.appium/java-client -->
<dependency>
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>9.0.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.13.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.11.1</version>
</dependency>

</dependencies>
<build>
<finalName>ftp_file_upload</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>${maven.source.plugin.version}</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
package com.testsigma.addons.web;

import com.testsigma.sdk.ApplicationType;
import com.testsigma.sdk.Result;
import com.testsigma.sdk.WindowsAction;
import com.testsigma.sdk.annotation.Action;
import com.testsigma.sdk.annotation.RunTimeData;
import com.testsigma.sdk.annotation.TestData;
import lombok.Data;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.openqa.selenium.NoSuchElementException;

import java.io.*;
import java.net.URL;
import java.nio.file.Paths;

@Data
@Action(actionText = "FTP: Connect to FTP server and upload a file. FTP server details: Host: Host-Name, Port: Port-No, UserName: User-Name, Password: User-Password, Upload from Local-File-Path to Remote-Directory(ex: /Users/username/Downloads) with file name Remote-File-Name. Uploaded file path will be stored in runtime variable: variable-name",
description = "Uploads a file from a local file or URL to a remote server using FTP, and stores the uploaded file path in a runtime variable.",
applicationType = ApplicationType.WEB,
useCustomScreenshot = false)
public class FTPUploadFile extends WindowsAction {

@TestData(reference = "Host-Name")
private com.testsigma.sdk.TestData hostName;

@TestData(reference = "Port-No")
private com.testsigma.sdk.TestData portNo;

@TestData(reference = "User-Name")
private com.testsigma.sdk.TestData userName;

@TestData(reference = "User-Password")
private com.testsigma.sdk.TestData userPassword;

@TestData(reference = "Local-File-Path")
private com.testsigma.sdk.TestData localFilePath; // Local file path or URL

@TestData(reference = "Remote-Directory")
private com.testsigma.sdk.TestData remoteDirectory; // Remote directory to upload to

@TestData(reference = "Remote-File-Name")
private com.testsigma.sdk.TestData remoteFileName; // Remote file name after upload

@TestData(reference = "variable-name", isRuntimeVariable = true)
private com.testsigma.sdk.TestData uploadedFilePath; // Runtime variable for storing uploaded file path

@RunTimeData
private com.testsigma.sdk.RunTimeData runTimeData;

@Override
public com.testsigma.sdk.Result execute() throws NoSuchElementException {
logger.info("Initiating execution for FTP file upload");

String user = userName.getValue().toString();
String host = hostName.getValue().toString();
String port = portNo.getValue().toString();
String password = userPassword.getValue().toString();
String localFile = localFilePath.getValue().toString();
String remoteDir = remoteDirectory.getValue().toString();
String remoteFile = remoteFileName.getValue().toString();

FTPClient ftpClient = new FTPClient();
File localFileToUpload = null;
try {
// Determine if the localFile is a URL or a local path
if (localFile.startsWith("http://") || localFile.startsWith("https://")) {
localFileToUpload = downloadFile(localFile);
} else {
localFileToUpload = new File(localFile);
}


// Verify the local file exists
if (!localFileToUpload.exists()) {
setErrorMessage("Local file not found: " + localFile);
return Result.FAILED;
}

// Append extension if remote file name has no extension
if (!remoteFile.contains(".")) {
String localFileName = localFileToUpload.getName();
int dotIndex = localFileName.lastIndexOf('.');
if (dotIndex > 0) {
String extension = localFileName.substring(dotIndex);
remoteFile += extension;
logger.info("Remote file name updated to include extension: " + remoteFile);
} else {
setErrorMessage("Local file does not have an extension: " + localFileName);
return Result.FAILED;
}
}

ftpClient.connect(host, Integer.parseInt(port));
boolean loginSuccess = ftpClient.login(user, password);

if (!loginSuccess) {
setErrorMessage("Failed to login to FTP server. Check credentials.");
return Result.FAILED;
}

ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

boolean changedDir = ftpClient.changeWorkingDirectory(remoteDir);
if (changedDir) {
logger.info("Changed to directory: " + remoteDir);
} else {
setErrorMessage("Remote directory does not exist: " + remoteDir);
return Result.FAILED;
}

try (InputStream inputStream = new FileInputStream(localFileToUpload)) {
logger.info("Start uploading file to " + remoteDir + "/" + remoteFile);
boolean done = ftpClient.storeFile(remoteFile, inputStream);

if (done) {
String outputPath = remoteDir + "/" + remoteFile;
runTimeData.setValue(outputPath);
runTimeData.setKey(uploadedFilePath.getValue().toString());
setSuccessMessage("File uploaded successfully to: " + outputPath);
return Result.SUCCESS;
} else {
setErrorMessage("File upload failed for: " + localFile);
return Result.FAILED;
}
}

} catch (IOException ex) {
setErrorMessage("FTP Error: " + ex.getMessage());
logger.warn("Exception occurred: " + ex);
return Result.FAILED;
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
logger.info("FTP connection closed.");
} catch (IOException ex) {
logger.warn("Error while closing FTP connection: " + ex);
}
if (localFileToUpload != null && localFile.startsWith("http")) {
localFileToUpload.delete(); // delete temp file if it was a download
}
}
}

private File downloadFile(String fileUrl) throws IOException {
URL url = new URL(fileUrl);
String fileName = Paths.get(url.getPath()).getFileName().toString();
File tempFile = File.createTempFile("downloaded-", fileName);
try (InputStream in = url.openStream();
OutputStream out = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
return tempFile;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
testsigma-sdk.api.key=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIyMjMyMmM2Ni04NWYzLWIyN2UtN2FiOS0zM2U2M2Q4OWM1MGIiLCJ1bmlxdWVJZCI6IjQwMDQiLCJpZGVudGl0eUFjY291bnRVVUlkIjoiMzUifQ.lBjbuuWPNsHATQprYpnMTMXHpRarskoHsUtRkc2wgkPq4hmDlr8ivQJu2PHxx8pEkoPcF_fwtvSNkpqkdGov7A
Loading