getContentLength doesn't work on android for FTP url - java

Following code prints length -1 for filesize on android, but it works fine on desktop JAVA.
I'm using Android 2.2.
URL url1 = null;
URLConnection uconn = null;
try {
url1 = new URL("ftp://FTPHOST/file.zip");
uconn = url1.openConnection();
uconn.setDoInput(true);
int len= uconn.getContentLength();
int headersize = uconn.getHeaderFields().size();
System.out.println("******************************* "+len);
} catch (Exception e) {
e.printStackTrace();
}
return null;
Let me know if any workaround in android to get filesize..

The Android platform's url connection code uses a different base (Apache HTTP client) under the hood, rather than the Oracle JVM's implementation. Apache HTTP client doesn't natively support FTP download the way the desktop JVM does.
The desktop JVM uses a class that was historically named sun.net.ftp.FtpClient for that FTP functionality. None of the sun classes are available on Android, so that doesn't work. You'll need to get your own FTP client.

Related

sometimes I unable to connect to connect to socket using php java bridge

we are using java bridge from PHP application to connect to java application.
But at times, connection get failed to connect. Below is the fucntion used to connect. I am not getting what the issue is. Sometimes it works and sometimes it fails to connect. Any persistent connection issues or count is set?
function open() {
$errno = null;
$errstr = null;
$socket = JAVA_PERSISTENT_SERVLET_CONNECTIONS ?
pfsockopen("{$this->ssl}{$this->host}", $this->port, $errno, $errstr, 20) :
fsockopen("{$this->ssl}{$this->host}", $this->port, $errno, $errstr, 20);
if (!$socket)
throw new java_ConnectException("Could not connect to the J2EE server {$this->ssl}{$this->host}:{$this->port}. Please start it. Or define('JAVA_HOSTS', 8080); define('JAVA_SERVLET', false); before including 'Java.inc' and try again. Error message: $errstr ($errno)\n");
stream_set_timeout($socket, -1);
return $socket;
}
function java_HttpHandler($protocol, $ssl, $host, $port) {
parent::java_SimpleHttpHandler($protocol, $ssl, $host, $port);
try {
$this->socket = $this->open();
} catch (Exception $e) {
$cogLink = "http://xxxx.xx.com/products/sup_products.asp?prod_id=81174";
echo "eeeeerrrr";
}
}
Any persistent connection issues or count is set?
Most likely the back-end ran out of handles. Please note that, in order to obtain a persistent connection to a java "continuation", you'll have to send a servlet engine a POST request first. After that you can pfsockopen() to the java "continuation" the servlet engine has returned and use protocol request
(F p="A"/)
to recycle- and
(F p="F"/)
to put the "continuation" back to the pool.
I have checked the Java.inc code and it doesn't contain the code you have posted. Therefore I assume that you have written custom code to emulate Java.inc.
If so, please make sure to no exceed the bridge thread pool size (20 by default).

Sending a String via Serial COMM

I'm developing a system with Gemalto BG5ST (a java modem).
I need to send a string sent via http GET request to the Serial Port.
This string is stored, but the problem is that I need the data to be int or byte in order to write in the Outputstream.
Is there anyway to go around this?
OutputStream outStream = null;
String strCOM = "comm:COM0;blocking=off;baudrate=115200";//autocts=off;autorts=off
CommConnection commConn = (CommConnection)Connector.open(strCOM)
inStream = commConn.openInputStream();
outStream = commConn.openOutputStream();
Working with IDE 1.3 due to modem restrictions.
Thanks!
str.getBytes() - 1.1 version, used default charset
str.getBytes("UTF-8") - 1.1 version
I did this to solve the issue.
byte[] data = v1.getBytes();
int j;
for (j=0;j<data.length;j++)
{
outStream.write(data[j]);
System.out.println(data[j]);
}
Thanks guys.

In java is there a way to tell on which physical computer a file resides?

I have an eclipse RCP product that is run by multiple people at our company. All PCs are running some version of Windows. We have access to a shared PC which different people have mapped to different drive letters. That means the same file may be referred to in many different ways depending on the PC on which program is run. E.g.
\communalPC\Shared\foo.txt
Y:\Shared\foo.txt
Z:\Shared\foo.txt
I want to programmatically check if an arbitrary file is on the communnal PC. Is there a robust way to do this in java?
Our current solution below is a bit of a hack It is not robust due to people mapping to different drive letters, changing drive letters, not-portable etc.
private static boolean isOnCommunalPc(File file) {
if(file.getAbsolutePath().toLowerCase().startsWith("\\\\communalPC")) {
return true;
}
if(file.getAbsolutePath().toLowerCase().startsWith("y:")){
return true;
}
if(file.getAbsolutePath().toLowerCase().startsWith("z:")){
return true;
}
return false;
}
Java cannot tell the difference of which machine the file is on, as Windows abstracts that layer away from the JVM. You can, however be explicit with your connection.
Is there a reason why you couldn't have an ftp or http server (or even a custom java server!) on the communal pc, and to access it via a hostname or an ip? That way, it doesn't matter where the user has mapped the network drive, you connected via a static address.
Accessing a remote file in Java is as easy as:
URL remoteUrl = new URL(String.format("%s/%s", hostName, fileName));
InputStream remoteInputStream remoteUrl.openConnection().getInputStream();
//copyStreamToFile(remoteInputStream, new File(destinationPath), false);
If you need the file to be local for a library or code you would prefer not to change, you could:
void copyStreamToFile(InputStream in, File outputFile, boolean doDeleteOnExit) {
//Clean up file after VM exit, if needed.
if(doDeleteOnExit)
outputFile.deleteOnExit();
FileOutputStream outputStream = new FileOutputStream(outputFile);
ReadableByteChannel inputChannel = Channels.newChannel(in);
WritableByteChannel outputChannel = Channels.newChannel(outputStream);
ChannelTools.fastChannelCopy(inputChannel, outputChannel);
inputChannel.close();
outputChannel.close()
}
EDIT Accessing a remote file via Samba with JCIFS is as easy as:
domain = ""; //Your domain, only set if needed.
NtlmPasswordAuthentication npa = new NtlmPasswordAuthentication(domain, userName, password);
SmbFile remoteFile = new SmbFile(String.format("smb://%s/%s", hostName, fileName), npa);
//copyStreamToFile(new SmbFileInputStream(remoteFile), new File(destinationPath), false)
This will probably be the most pragmatic solution, as it requires the least amount of work on the Windows server. This plugs into the existing server framework in Windows, instead of installing more.

android download http video file

I have a very simple program http downloading program as following. The file is very small, like 200K.
The problem is that when I use 3G connection, sometimes one download will be stucked for a very long time. But I can watch youtube very well with 3G connection which means the 3G network is good. Is there anything wrong with the code?
There is no problem when I use wifi connection.
for (int chunkno = 0; chunkno < 10000000; ++chunkno)
{
try
{
AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
HttpGet request = new HttpGet("http://ipaddress/vbr_100.mp4");
HttpResponse response = client.execute(request);
recvbytes = response.getEntity().getContentLength();
File f = new File(Environment.getExternalStoragePublicDirectory("bill"), "f");
if (!f.exists())
{
f.createNewFile();
}
response.getEntity().writeTo(new FileOutputStream(f));
}
catch (IOException ex)
{
}
}
I would recommend you to use android DownloadManager package, which takes care of all issues related to huge files download.
Copied from the Android document site:
The download manager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots.
A very good example of using DownloadManager is provided here.
Hope this helps !!

Apache FTPClient - incomplete file retrieval on Linux, works on Windows

I have a java application on Websphere that is using Apache Commons FTPClient to retrieve files from a Windows server via FTP. When I deploy the application to Websphere running in a Windows environment, I am able to retrieve all of the files cleanly. However, when I deploy the same application to Webpshere on Linux, there are cases where I am getting an incomplete or corrupt files. These cases are consistent though, such that the same files will fail every time and give back the same number of bytes (usually just a few bytes less than what I should be getting). I would say that I can read approximately 95% of the files successfully on Linux.
Here's the relevant code...
ftpc = new FTPClient();
// set the timeout to 30 seconds
ftpc.enterLocalPassiveMode();
ftpc.setDefaultTimeout(30000);
ftpc.setDataTimeout(30000);
try
{
String ftpServer = CoreApplication.getProperty("ftp.server");
String ftpUserID = CoreApplication.getProperty("ftp.userid");
String ftpPassword = CoreApplication.getProperty("ftp.password");
log.debug("attempting to connect to ftp server = "+ftpServer);
log.debug("credentials = "+ftpUserID+"/"+ftpPassword);
ftpc.connect(ftpServer);
boolean login = ftpc.login(ftpUserID, ftpPassword);
if (login)
{
log.debug("Login success..."); }
else
{
log.error("Login failed - connecting to FTP server = "+ftpServer+", with credentials "+ftpUserID+"/"+ftpPassword);
throw new Exception("Login failed - connecting to FTP server = "+ftpServer+", with credentials "+ftpUserID+"/"+ftpPassword);
}
is = ftpc.retrieveFileStream(fileName);
ByteArrayOutputStream out = null;
try {
out = new ByteArrayOutputStream();
IOUtils.copy(is, out);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(out);
}
byte[] bytes = out.toByteArray();
log.info("got bytes from input stream - byte[] size is "+ bytes.length);
Any assistance with this would be greatly appreciated.
Thanks.
I have a suspicion that the FTP might be using ASCII rather than binary transfer mode, and mapping what it thinks are Window end-of-line sequences in the files to Unix end-of-lines. For files that are really text, this will work. For files that are really binary, the result will be corruption and a slightly shorter file if the file contains certain sequences of bytes.
See FTPClient.setFileType(...).
FOLLOWUP
... so why this would work on Windows and not Linux remains a mystery for another day.
The mystery is easy to explain. You were FTP'ing files from a Windows machine to a Windows machine, so there was no need to change the end-of-line markers.

Categories

Resources