commons-net FTPClient.retrieveFileStream() returns wrong result - java

I have a Problem with commons-net FTPClient. If I download a file from my ftp server wirth retrieveFileStream() it works, but I get the result '150 Opening BINARY mode data connection for ...'. If I call noop() I get '226 Transfer complete' as result. For every following operation I get the result of the prvious operation.
I found out, that FTPClient reads results until end of line, if there are two result lines (as after retrieveFileStream()), I get the second one after the next command. I did a workaround by overriding FTPClient.retrieveFileStream() like this:
public static void main(String[] args){
try {
MyFTPClient ftpClient = new MyFTPClient();
try {
ftpClient.connect(ftphost, 21);
if(!ftpClient.login( ftpuser, ftppassword )){
throw new RuntimeException(ftpClient.getReplyString());
}
if(!ftpClient.changeWorkingDirectory("in")){
throw new RuntimeException(ftpClient.getReplyString());
}
FTPFile[] files = ftpClient.listFiles();
for(FTPFile file: files){
if(file.getName().startsWith(FILENAME) && (file.getType() == FTPFile.FILE_TYPE)){
InputStream in = ftpClient.retrieveFileStream(file.getName());
CsvFile csvFile = new CsvFile(in, "ISO-8859-1", ';', "yyyyMMdd", "#.00", Locale.US, false);
in.close();
in = null;
System.out.println(ftpClient.getReplyString());
System.out.println(ftpClient.readLine());
System.out.println(ftpClient.rnfr(file.getName()));
System.out.println(ftpClient.getReplyString());
System.out.println(ftpClient.rnto("x" + file.getName()));
System.out.println(ftpClient.getReplyString());
}
}
if(!ftpClient.logout()){
throw new RuntimeException(ftpClient.getReplyString());
}
} finally {
ftpClient.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static class MyFTPClient extends FTPClient{
public String readLine(){
try {
__getReplyNoReport();
} catch (IOException e) {
}
return getReplyString();
}
}
The call of the method readLine() gets me the additional Line of result.
But is this a bug of FTPClient or is it a problem of my ftp-server? The Problem of that workaround is, that the method blocks, if there is only one line of response.
Thanx for your help
Stephan

Sometimes it helps, reading the manual. A call of completePendingCommand() works

Related

Upload file using Apache FTP Client does not work

I have read a half dozen threads regarding this and I'm no where closer to a solution. No matter what I change I get ftp return code 500 "The command was not accepted and the requested action did not take place." and I'm not sure how to debug that.
This is my site and I can connect with CoreFTP and read and write, so it does not seem to be a permissions issue. I've tried two different accounts, with this code and CoreFTP. One writes to the root and another is pointed to an "image_in" folder.
imageData is a byte array with a length of 166578 and stream has the same length after the InputStream call. storeFile() always returns false with a return code of 500.
One thread implied enterLocalPassiveMode() and enterRemotePassiveMode() were the culprits, but I have tried this code both with and without those lines and still I get a 500 return code.
Any idea what I'm missing?
Greg
class ImageUploadTask extends AsyncTask <Void, Void, String>{
#Override
protected String doInBackground(Void... unsued) {
try {
boolean status = false;
try {
FTPClient mFtpClient = new FTPClient();
String ip = "my domain dot com";
String userName = "ftp79815757-0";
String pass = "my password";
mFtpClient.connect(InetAddress.getByName(ip));
mFtpClient.login(userName, pass);
int reply = mFtpClient.getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
//one thread said this would do the trick
mFtpClient.enterLocalPassiveMode();
mFtpClient.enterRemotePassiveMode();
InputStream stream = new ByteArrayInputStream(imageData);
mFtpClient.changeWorkingDirectory("/images_in");
String currdir = mFtpClient.printWorkingDirectory();
if (!mFtpClient.storeFile("remoteName.jpg", stream)) {
Log.e("FTPUpload", String.valueOf(mFtpClient.getReplyCode()));
}
stream.close();
mFtpClient.disconnect();
}
else {
Log.e("FTPConnected", String.valueOf(reply));
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(),
"Error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
You forgot to set file type
mFtpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
If it still doesn't work then you have following options:
If you insist on using Apache FTP Client then follow this example
Or you could try this example
The second example worked in my case.
You need to use: enterLocalPassiveMode
mFtpClient.enterLocalPassiveMode();
If you then do other operations, you might have to go back active with enterLocalActiveMode.

Csv file is empty when I writing content

I am trying write to a csv file. After the execution of the code bellow the csv file is still empty.
File is in folder .../webapp/resources/.
This is my dao class:
public class UserDaoImpl implements UserDao {
private Resource cvsFile;
public void setCvsFile(Resource cvsFile) {
this.cvsFile = cvsFile;
}
#Override
public void createUser(User user) {
String userPropertiesAsString = user.getId() + "," + user.getName()
+ "," + user.getSurname() +"\n";;
System.out.println(cvsFile.getFilename());
FileWriter outputStream = null;
try {
outputStream = new FileWriter(cvsFile.getFile());
outputStream.append(userPropertiesAsString);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public List<User> getAll() {
return null;
}
}
This is a part of beans.xml.
<bean id="userDao" class="pl.project.dao.UserDaoImpl"
p:cvsFile="/resources/users.cvs"/>
Program compiles and doesn't throw any exceptions but CSV file is empty.
If you're running your app in IDE, the /webapp/resources used for running app will differ from the /webapp/resources in your IDE. Try to log full path to file and check there.
try using outputStream.flush() as the final statement in the first of the try block.
I think you're looking at the wrong file. If you specify an absolute path /resources/users.cvs, then it probably won't be written into the a folder relative to the webapp. Instead, it will be written to /resources/users.cvs
So the first step is to always log an absolute path to make sure the file is where you expect it.
Try with this code, it will at least tell you where the problem lies (Java 7+):
// Why doesn't this method throw an IOException?
#Override
public void createUser(final User user)
{
final String s = String.format("%s,%s,%s",
Objects.requireNonNull(user).getId(),
user.getName(), user.getSurname()
);
// Note: supposes that .getFile() returns a File object
final Path path = csvFile.getFile().toPath().toAbsolutePath();
final Path csv;
// Note: this supposes that the CSV is supposed to exist!
try {
csv = path.toRealPath();
} catch (IOException e) {
throw new RuntimeException("cannot locate CSV " + path, e);
}
try (
// Note: default is to TRUNCATE the destination.
// If you want to append, add StandardOpenOption.APPEND.
// See javadoc for more details.
final BufferedWriter writer = Files.newBufferedWriter(csv,
StandardCharsets.UTF_8);
) {
writer.write(s);
writer.newLine();
writer.flush();
} catch (IOException e) {
throw new RuntimeException("write failure", e);
}
}

Handle java.nio.file.AccessDeniedException

I'm using this code to read value from a file.
public String getChassisSerialNumber() throws IOException
{
File myFile = new File("/sys/devices/virtual/dmi/id/chassis_serial");
byte[] fileBytes;
String content = "";
if (myFile.exists())
{
fileBytes = Files.readAllBytes(myFile.toPath());
if (fileBytes.length > 0)
{
content = new String(fileBytes);
}
else
{
return "No file";
}
}
else
{
return "No file";
}
return null;
}
I get this error:
java.nio.file.AccessDeniedException: /sys/devices/virtual/dmi/id/chassis_serial
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:84)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.newByteChannel(Files.java:407)
at java.nio.file.Files.readAllBytes(Files.java:3149)
How I can handle this error? Because now I the code stops execution? Is there some better way without interruption the code execution?
You have to use try-catch, either within getChassisSerialNumber() on when calling it. E.g.
try {
getChassisSerialNumber();
} catch (java.nio.file.AccessDeniedException e) {
System.out.println("caught exception");
}
OR
try {
fileBytes = Files.readAllBytes(myFile.toPath());
} catch (java.nio.file.AccessDeniedException e) {
return "access denied";
}
This way your program does not terminate.
For a clean design you should either return null in cases you could not read the file (returning "magic strings like "No file" or "access denied" are no good design, because you cannot differentiate if this string came from the file or not) or catch the exception outside of the method (my first example).
Btw. by just putting the content of the file into the content variable you don't return it (i.e., replace content = new String(fileBytes); with return new String(fileBytes);)
public String getChassisSerialNumber()
{
File myFile = new File("/sys/devices/virtual/dmi/id/chassis_serial");
if (myFile.exists())
{
byte[] fileBytes;
try {
fileBytes = Files.readAllBytes(myFile.toPath());
} catch (java.nio.file.AccessDeniedException e) {
return null;
}
if (fileBytes != null && fileBytes.length > 0)
{
return new String(fileBytes);
}
}
return null;
}
You should catch the exception instead of throwing it. I think that you need to put a try-catch block around the call to the method getChassisSerialNumber.
Something like this should work in your case:
String result = null;
try {
result = getChassisSerialNumber();
} catch (java.nio.file.AccessDeniedException ex) {
// do something with the exception
// you can log it or print some specific information for the user
}
return result; // if the result is null, the method has failed
In order to understand better this kind of things you should have a look to this page

How to open/pass a file into XMLEventReader

I'm trying to create a program that will read in an XML-based file and that will basically rewrite it in a more human friendly way, but I keep running into XMLStreamExceptions.
Here is what I have now
`import java.io.File;
/* main purpose of this class is to read and write an XML document
using tenants of STaX parsing. Eventually this should turn into a
class that will trim all but the outer 20% of the page
*/
public class XMLReader {
public static void main(String args[]) {
XMLInputFactory factory = XMLInputFactory.newInstance();
System.out.println("FACTORY:" + factory);
/*
//TODO: make input and output file take args from command line
using the programs mike sent as a reference.
File file =null;
if(args.length > 0) {
file = new File(args[0]);
}
*/
InputStream in = null; //initializing the file we will read
XMLEventReader reader = null; //intializing the eventreader
try {
in = new FileInputStream("/home/bzifkin/Proteus2/homer/src/main/java/ciir/proteus/parse/1105979_djvu.xml");
} catch (FileNotFoundException e) {
System.out.println("Could not find the file. Try again.");
}
try {
reader = factory.createXMLEventReader(in);
}
catch (XMLStreamException e) {
System.out.println("There was an XML Stream Exception, whatever that means");
}
}
}
This is the stack trace I get on the XMLStreamException
Message: expected start or end tag at com.sun.xml.internal.stream.XMLEventReaderImpl.nextTag(XMLEventReaderImpl.java:235)
at ciir.proteus.parse.XMLReader.main(XMLReader.java:61)
If I understand the comments right, you get a FileNotFoundException first, then XMLStreamException.
That sounds reasonable, because if opening the file fails, your code is printing an error message, but continues to process the undefined (null) InputStream "in".
Do something like this instead:
try {
in = new FileInputStream("/home/bzifkin/Proteus2/homer/src/main/java/ciir/proteus/parse/1105979_djvu.xml");
try {
reader = factory.createXMLEventReader(in);
}
catch (XMLStreamException e) {
System.out.println("There was an XML Stream Exception, whatever that means");
}
} catch (FileNotFoundException e) {
System.out.println("Could not find the file. Try again.");
}

How to get over Error when Reading from File into Java

My problem is in the following code.
The problem is that when I call the alreadyUser(String username) if the file doesn't exist on the system already, it gives the FileNotFoundException. I want to get over this error and I can not figure it out.
So at startup of the app the system asks for uname and pass. Then the alreadyUser method is called and it gives the error if the file is not already created hardly (I create it manually for example). And the next time I start the program if the file is already there it must not be switched with new, because the old data will be gone ofc :)
public final class TinyBase {
final static String FILENAME = "KEYVALUES.txt";
static FileOutputStream fos = null;
static FileInputStream fis = null;
protected static void createUser(String username, String password)
protected static boolean loadUser(String username, String password)
protected static boolean alreadyUser(String username) {
String encode = new String(username);
String compare = null;
boolean flag = false; // true - ok no such user ; false - fail username
// already in use
try {
/* ERROR IS HERE */
fis = new FileInputStream(FILENAME);
/* ERROR IS HERE */
byte[] buffer = new byte[fis.available()];
while (fis.read(buffer) != -1) {
compare = new String(buffer);
if (compare.contains(encode)) {
flag = true;
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
return flag;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
}
Check if the file exists using -
File f = new File(filePathString);
if(f.exists()) { /* do something */ }
I guess, what you need according to your snapshot, is to handle FileNotFoundCase properly :
// ....
} catch (FileNotFoundException e) {
Log.d("no settings for the user - assuming new user");
flag = true;
}
BTW, you need to fix your finally block, in case of prior exception your fis may be null, so to avoid NullPointerException you may need an extra check :
if (fis != null) {
fis.close();
}
UPDATE
Here is sketch of what you may need based on my understanding of your problem :
// ... somewhere at startup after username/pass are given
// check if file exists
if (new File(FILENAME).isFile() == false) { // does not exist
fos = new FileOutputStream(FILENAME); // will create
// file for you (not subfolders!)
// write content to your file
fos.close();
}
// by this point file exists for sure and filled with correct user data
alreadyUser(userName);

Categories

Resources