downloading file from FTP gets stuck when running Jenkins - java

I'm trying to download a file from FTP in my test.
When I'm running this from my local PC or on BrowserStack it works perfectly but when I upload it to jenkins it gets stuck in the line.
I can't understand what is the difference why doesn't it run on Jenkins?
I managed to create a connection to the FTP. the code shown below is the method that downloads the file.
boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
public static File downloadFileFromFtp(String fileName, String ftpFilePath, String downloadDirectory, String fileExtension, ExtentTest test) throws Exception {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(AutomationPropeties.ftpHost, Integer.valueOf(AutomationPropeties.ftpPort));
ftpClient.login(AutomationPropeties.ftpUsername, AutomationPropeties.ftpPassword);
ftpClient.enterLocalPassiveMode();
System.out.println("loged in ftp");
if (ftpClient.isConnected()) {
test.log(LogStatus.INFO, "Connected Succesfuly to ftp server.");
System.out.println("loged in ftp");
} else {
test.log(LogStatus.INFO, "Failed connecting to ftp.");
System.out.println("not loged in ftp");
}
String remoteFile = ftpFilePath + fileName + ".xlsx";
System.out.println(remoteFile);
// File downloadFile = new File(downloadDirectory+fileName+".xlsx");
File downloadFile = File.createTempFile(fileName, ".xlsx");
System.out.println("reached the try");
try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile))) {
System.out.println("finished with the output");
boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
System.out.println("retrive the file & conection closed");
if (success) {
test.log(LogStatus.PASS, "File was downloaded succesfuly");
} else {
test.log(LogStatus.FAIL, "Failed to download file");
}
} finally {
ftpClient.logout();
ftpClient.disconnect();
}
return downloadFile;
}

Perhaps the Jenkins FTP plugin is what you need. Jenkins can be defined with worker bee (so much better than slave, don't you think?) servers so your job may run on different physical servers.
If you look into the plugin please report back if that helped.
Update
Use:
curl -O ftp://server/path/to/file

This is Mukul from BrowserStack. We have recently released a Jenkins plugin that might help you out.

Related

apache FTPS with proxy get timeout when transferring file

I am trying to use an ftps client with proxy.
I am using this library by apache: org.apache.commons.net.ftp;
The problem is, that it looks like when I set proxy to the ftps client, it is connecting and also doing login, but gets connect timed out when trying to transfer the file.
though if I don't set proxy on the ftps client, the file is being written succesfully.
just to mention, if I use normal FTP client (with proxy, i.e. new FTPClient()), and not FTPS client (i.e. new FTPSClient()), it also works.
This is how I create the ftps client:
FTPClient ftpClient = new FTPSClient();
ftpClient.setConnectTimeout(timeout);
ftpClient.setCopyStreamListener(new FileCopyListener(context, "Transfer file using ftp."));
// setting the proxy:
ftpClient.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(OUTBOUND_HTTP_PROXY_HOST, OUTBOUND_HTTP_PROXY_PORT)));
ftpClient.setRemoteVerificationEnabled(false);
// connecting:
ftpClient.connect(host, port);
// login
ftpClient.login(username, password)
// some file configuration
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.setBufferSize(DataSourceProperties.BUFFER_SIZE);
// has encryption
((FTPSClient) ftpClient).execPBSZ(0);
((FTPSClient) ftpClient).execPROT("P");
// now trying to transfer file
for (File file : files) {
try (InputStream fileInputStream = new FileInputStream(file)) {
String remoteFileName = file.getName();
if (ftpClient.storeFile(remoteFileName, fileInputStream)) { // *** THIS IS WHERE I GET THE TIMEOUT
logger.info("File uploaded successfully");
} else {
throw new Exception(errorMessage);
}
traceLogger.info(LogFactory.createLog(stepId, "Complete uploading file", parameters));
}
}
any idea?

Can not read file when run within jar file

I have an akka http service. I simply return the api documentation for a get request. The documentation is in html file.
It all works fine when run within the IDE. When I package it as a jar I get error 'resource not found'. I am not sure why it can not read the html file when hosted in a jar and works fine when in IDE.
Here is the code for the route.
private Route topLevelRoute() {
return pathEndOrSingleSlash(() -> getFromResource("asciidoc/html/api.html"));
}
The files are located in resource path.
I have got this working now.
I am doing this.
private Route topLevelRoute() {
try {
InputStreamReader inputStreamReader = new InputStreamReader(getClass().getResourceAsStream("/asciidoc/html/api.html"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//Get the stream input into string builder
reader.lines().forEach(s -> strBuild.append(s));
inputStreamReader.close();
bufferedReader.close();
//pass the string builder as string with contenttype set to html
complete(HttpEntities.create(ContentTypes.TEXT_HTML_UTF8, strBuild.toString()))
} catch (Exception ex) {
//Catch any exception here
}
}

Code runs on localhost not on app server

I am developing a code for xcel generation and download using apache poi. LocalHost server and app server is jboss. When i run the code on localhost, a temp folder is generated in jboss's deployment folder and in that the xcel is generated and then downloaded through frontend. I am using java spring angularjs and html. This runs fine on localhost but after deploying on app server the xcel is not downloaded and it gives 500:internal server error.
angularjs controller code:
$scope.generateExcel=function(sDate,eDate,doc,search)
{
console.log("hello");
var sDate = document.getElementById('sD').value
var eDate = document.getElementById('eD').value
$scope.obj.sDate = sDate;
$scope.obj.eDate = eDate;
$scope.obj.iou = doc;
$scope.obj.du = search;
console.log($scope.obj);
$http.post('abc/generateExcel',$scope.obj).then(function()
{
//console.log(path);
$window.location.href="/ProjectName/file_name.xls";
})
.error(function()
{
console.log("Error!!");
});
};
java code:
//Method
public HttpServletResponse generateExcel ( HttpServletRequest request , HttpServletResponse response, String sD, String eD, String doc, String search)
{
//EXCEL GENERATION HERE
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=filename.xls");
//Path Specification
String path = request.getRealPath("/file_name.xls");
//System.out.println("Here...");
System.out.println(path);
FileOutputStream fileOut2 = new FileOutputStream(path);
workbook.write(fileOut2);
/*returning response*/
}
It's difficult to answer this unless one knows what's the error you are getting on the server side. Put your server code in a try-catch block. Rerun the code, and check the server logs. Paste them here.
try{
String path = request.getRealPath("/file_name.xls");
//System.out.println("Here...");
System.out.println(path);
FileOutputStream fileOut2 = new FileOutputStream(path);
workbook.write(fileOut2);
} catch(Exception e){
e.printStackTrace(); // this should print some error in server logs
}

FTP exception 501 "pathname" more than 8 characters

I am trying to access a file via a URI using the FTP protocol. For obvious security reasons I had to make some changes but this is where the problems seem to be coming from.
My URI is as follows:
ftp://user:pasword#host.net/u/Bigpathname/XYZ/ABC/BigPathname/bigpathname/xyz/abc/MY_LOG.LOG
And I see this exception:
sun.net.ftp.FtpProtocolException: CWD Bigpathname:501 A qualifier in "Bigpathname" is more than 8 characters
This is really confusing as I can access the file from a Windows 7 command line with the CD command just fine. Both one directory at a time and as a full path.
I found one article mentioning that MVS file names must be 8 or fewer characters but this does not explain how I can get to these same files from my command line! They do exist there is data there that I can download manual but I can not get there via a URI in Java.
PS I use .toURL().openStream() to get files on my local machine just fine, it only fails when I try to get them from my server.
EDIT October 1st
I am able to access files on the MVS host using FileZilla and the basic FTP client from the Windows 7 command line - but I still cannot get them from a URI/URL. I downloaded a very basic Java built FTP client and tried accessing the same file in my program from there and the path works but because my file name has a dot in it "MY_LOG.LOG" I am getting File does not exist 501 Invalid data set name "MY_LOG.LOG". Use MVS Dsname conventions. I am utterly perplexed by this...
EDIT Ocotober 1st afternoon :)
OK I finally got it to work with a FTP client in my Java code - but I still want to use the URL class as I have logs on both local and remote machines. Is there a way to encode a URL string so that it can retrieve a file from a remote machine with the FTP protocol? I am not sure how it works in the Java URL class but in the FTP client I had to use the CWD and then the RETR command.
If I can do this then I have one solution for getting all my logs, otherwise I will have to detect if it is a file or ftp URL and then behave differently. Not the end of the world but not what I want...
The code that tries to get the file with just a URL is as follows: (sysc is a valid host)
void testFTP()
{
String ftp = "ftp://user:pword#sysc/u/Xxxxxxxxxx/ICS/YT7/XxxxxXxxxxxxx/xxxxxxxxx/logs/xxxxxxxx/XX_YT.LOG";
try
{
URI uri = new URI(ftp);
URL ftpFile = uri.toURL();
BufferedReader in = new BufferedReader(new InputStreamReader(ftpFile.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
In this case I think the problem is also Server Related, It all works fine for me with Filezilla Server except when the filename length(including directories) exceeds 255 chars but if you want to use the URL class with another FTP you must override or implement your own URLStreamHandlerFactory.
URL.setURLStreamHandlerFactory(...);
I haven't found any for my favorite java FTP Client witch is Apache one so I have developed one but may need a few touch ups.
package net.custom.streamhandler.apacheftp;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class ApacheURLStreamHandlerFactory implements URLStreamHandlerFactory {
public URLStreamHandler createURLStreamHandler(String protocol) {
//this will only override the chosen protocol
if ( protocol.equalsIgnoreCase("ftp") )
return new CustomHandler();
else
return null;
}
}
class CustomHandler extends URLStreamHandler {
protected URLConnection openConnection(URL url)
throws IOException {
return new CustomURLConnection(url);
}
}
class CustomURLConnection extends URLConnection {
int reply;
FTPClient ftp = new FTPClient();
InputStream in;
static int defaultPort = 21;
static String defaultPath = "/";
CustomURLConnection ( URL url)
throws IOException {
super( url );
}
synchronized public void connect() throws IOException {
try {
int port;
if ((port = url.getPort()) == -1 )
port = defaultPort;
ftp.connect(url.getHost(), port);
String login = "anonymous";
String password = "";
if(url.getAuthority().indexOf(':')>-1 &&
url.getAuthority().indexOf('#')>-1){
String []auxArray = url.getAuthority().replaceAll("#", ":").split(":");
login = auxArray[0];
password = auxArray[1];
}
ftp.login(login, password);
reply = ftp.getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
System.out.println("Connected Apache Success");
} else {
System.out.println("Connection Apache Failed");
ftp.disconnect();
}
in = ftp.retrieveFileStream(url.getFile());
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
connected = true;
}
synchronized public InputStream getInputStream()
throws IOException {
if (!connected)
connect();
return ( in );
}
}
*Keep in mind that you can implement new ways to handle different protocols for the java.net.URL this way.
Your code...
...
{
String ftp = "ftp://user:pword#sysc/u/Xxxxxxxxxx/ICS/YT7/XxxxxXxxxxxxx/xxxxxxxxx/logs/xxxxxxxx/XX_YT.LOG";
try
{
URL.setURLStreamHandlerFactory(new ApacheURLStreamHandlerFactory());
...
G'Bye
**(To err is human, to forgive is divine)
Try using the short name for the path. Something like /U/BIGPAT~1/XYZ/ABC/BIGPAT~1/BIGPAT~1/XYZ/ABC/MY_LOG.LOG
You can find the short name for any directory longer than 8 characters with dir /x.
FTP clients are notoriously difficult to write given the variation of (and bugs in) server implementations.
I'm betting that MVS is not completely supported by sun.net.ftp.FtpClient, which is the class used under the hood when you call URL.openStream on an FTP URL.
The Apache Commons Net library should support MVS, but it sounds like you already found a working client.
Have you considered using an RMI for transporting the files that way you can give a direct path to the file as a parameter without the use of ftp then have the file sent back in a byte array.

testing whether embedded Mina FTPServer really started

i wrote programmatically a startup code of the apache Server like this:
public void _start()
{
String Path = "C:\\Dokumente und Einstellungen\\andjock\\Desktop\\ab";
File ftpDirectory = new File(Path);
ftpDirectory.mkdirs();
FtpServerFactory serverFactory = new FtpServerFactory();
ListenerFactory factory = new ListenerFactory();
factory.setPort(2221);
try {
serverFactory.addListener("default", factory.createListener());
PropertiesUserManagerFactory userFactory = new PropertiesUserManagerFactory();
File userFile = new File("C:\\Dokumente und Einstellungen\\andjock\\Desktop\\ftpusers.properties");
userFactory.setFile(userFile);
UserManager um = userFactory.createUserManager();
BaseUser user = new BaseUser();
user.setName("myNewUser");
user.setPassword("secret");
user.setHomeDirectory(Path);
um.save(user);
serverFactory.setUserManager(um);
FtpServer ftpServer = serverFactory.createServer();
ftpServer.start();
} catch (Exception e) {
Logger LOGGER = Logger.getLogger(TestapacheFtpServer.class);
LOGGER.log(Level.FATAL, "Unable to start test ftpserver", e);
}
How do i know that the server is really working ?
how can i access this apache Server , from the "outside"?
i tried with a telnet and ftp (ftp 127.0.0.1) on my machine but i received:
FTP: connect : unknown error code
does someone got any idea ? i just don't want to rely on the jvm log, but rather test it , and accesing the started it
i figure it out!! i wrote a client using the FTP client library (the apache commons library) to test connectivity and list the files ; something like that
FTPClient ftp = new FTPClient();
ftp.connect(InetAddress.getLocalHost(), 2221);// or "localhost" in your case
String loging_success = ftp.login("myNewUser", "secret") == true ? "success" : "failed";
System.out.println("login: "+ loging_success);
FTPFile[] files = ftp.listFiles();
System.out.println("Listed "+files.length+" files.");
for(FTPFile file : files) {
System.out.println(file.getName());
}

Categories

Resources