i have this code to download a single file .
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
public class NetTest {
public static void main(String[] args){
FTPClient client = new FTPClient( );
OutputStream outStream;
try {
this is the part of server and passwords .
client.connect( "servername" );
client.login("noman123", "pass");
String remoteFile = "/a.txt";
outStream = new FileOutputStream( "a.txt" );
simple fill downloading but error on this line
client.retrieveFile( remoteFile, outStream );
} catch(IOException ioe) {
System.out.println( "Error communicating with FTP server." );
} finally {
try {
client.disconnect( );
} catch (IOException e) {
System.out.println( "Problem disconnecting from FTP server" );
}
}
}
}
and it gives me errors like
i hope that u can understand the issue that i m facing now
java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:295)
at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
at java.io.BufferedWriter.flush(BufferedWriter.java:254)
at org.apache.commons.net.ftp.FTP.__send(FTP.java:496)
at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:470)
at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:547)
at org.apache.commons.net.ftp.FTP.port(FTP.java:872)
at org.apache.commons.net.ftp.FTPClient.openDataConnection(FTPClient.java:667)
at org.apache.commons.net.ftp.FTPClient.retrieveFile(FTPClient.java:1595)
at FtpDownloadDemo.main(FtpDownloadDemo.java:25)
turn off the firewall.in this issue
Make sure you can ping the server and log in manually, but assuming you're ok there, there's two additional things I would do.
1) Per the FTP Client documentation, check that you're really connected
// After connection attempt, you should check the reply code to verify success.
reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{ // print more complete error }
There's a full example here.
2) It could be since you're trying to get the remote file "/a.txt" you're trying to get to the root directory and your ftp server isn't set up to allow you access. Try just "a.txt" in whichever directory your ftp client is set to dump a user into.
The documentation on the given example code that you should call the enterLocalPassiveMode method of FTPClient if you are behind a firewall.
read this article http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7077696
WORK AROUND to solve this problem start program with
-Djava.net.preferIPv4Stack=true
Related
I'm trying to connect to my localhost kafka server from java function saved into Oracle database 19.3.
The problem is that i cannot reach the server. In database trace files i see that kafka library is using java.nio package to connect to server. Any connection attempt is ending with "Connection refused". I admit also that I can send data to topics from command line tool.
To check if my requests from database are incoming to localhost server at port 9092 i have run Hercules TCP Server and setup it to listen on this port. Then when i'm using my java function it nothing happens.
I write some "test" functions to make only simple connection to my local server, to see if there is some network problem.
The function where i use java.net package is working and i can see that i receive connection requests from database, but the function where i use java.nio package is returning always "Connection refused"
I have granted java.net.SocketPermission to my database user:
exec dbms_java.grant_permission( 'KAFKA', 'SYS:java.net.SocketPermission', '*', 'connect,resolve' );
commit;
Are there needed some special permissions to use java.nio package into oracle database java functions or maybe i'm doing something wrong?
Here are my java "test" functions code:
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "testTCP" AS
import java.net.Socket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class testTCP {
public static String conn_nio(){
String response;
try {
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 9092);
SocketChannel client = SocketChannel.open(hostAddress);
client.close();
response = "OK";
}
catch(Exception e){
response = "Message: " + e.getMessage() + " Cause: " + e.getCause();
}
return response;
}
public static String conn_net() {
String response;
try
{
Socket socket = new Socket( "localhost", 9092 );
socket.close();
response = "OK";
}
catch( Exception e )
{
response = "Message: " + e.getMessage() + " Cause: " + e.getCause();
}
return response;
}
}
Cannot reproduce. I pointed it to port 8080 of a local HTTP server which I started with
python -m SimpleHTTPServer 8080
and both connection methods are ok:
CREATE OR REPLACE FUNCTION test_net RETURN VARCHAR2 AS
LANGUAGE JAVA NAME 'testTCP.conn_net() return java.lang.String';
/
CREATE OR REPLACE FUNCTION test_nio RETURN VARCHAR2 AS
LANGUAGE JAVA NAME 'testTCP.conn_nio() return java.lang.String';
/
SELECT test_net FROM DUAL;
OK
SELECT test_nio FROM DUAL;
OK
I am trying to FTP a text file to mainframe using java. I am able to create a member in PDS using below code.
//Function to FTP the report
public void sendReport() throws IOException
{
FTPSClient ftp = null;
InputStream in = null;
String protocol="TLS";
//Connecting to mainframe server for ftp transfer
ftp = new FTPSClient(protocol);
ftp.connect(hostname);
ftp.login(user,password);
ftp.execPBSZ(0);
ftp.execPROT("P");
ftp.enterLocalPassiveMode();
ftp.setFileType(FTP.ASCII_FILE_TYPE);
int reply = ftp.getReplyCode();
System.out.println("Received Reply from FTP Connection:" + reply);
if (FTPReply.isPositiveCompletion(reply))
System.out.println("Connected To Mainframe");
else
System.out.println("Not connected to Mainframe..Check ID or Password");
//Setting mainframe PDS for reports
boolean success = ftp.changeWorkingDirectory("***Mainframe Directory***");
if (success)
System.out.println("Successfully changed PDS.");
else
System.out.println("Failed to change PDS. See Mainframe's reply.");
//Sending Report to mainframe PDS
File f1 = new File(dkReportName);
in = new FileInputStream(f1);
boolean done = ftp.storeFile("DKI"+dkReportName.substring(14,18), in);
in.close();
if (done)
System.out.println("FILE FTP SUCCESSFUL");
else
System.out.println("FILE FTP NOT SUCCESSFUL");
ftp.logout();
ftp.disconnect();
}
user,password and hostname variables are being set in appContext.xml.
However, I want to create a PS dataset.
Could anyone please suggest a way of doing it.
Based on your question, this is for the MVS file space and not USS.
When creating a dataset with FTP you need to give the host some information about files size, attributes, etc.
This page on IBM's website outlines a list of commands that you can execute to setup for the transfer. The basic sequence would be something like:
site cyl
site pri=5
site sec=5
site recfm=fb
and you can combine more than one command on a line:
site lrecl=80 blksize=3120
Execute these commands before the transfer and the file should be allocated with your desired characteristics.
Based on your coding example here is a sample that should work:
ftp.sendCommand("site",
"cyl pri=5 sec=5 recfm=fb filetype=seq lrecl=80 blksize=3120");
I have Arm processor which is AllWinner A13 ,RAM- 512mb, and OS- Linaro 13.01 Ubuntu (means debian). Now i m making Serial Communication program for /dev/ttyS0. i made simple program for Two Way Serial Communication in java with netbeans. In my processor i short rx-tx of ttyS0 for loop back coonection checking. Means what ever i send through Serial port that i get return back. but i get error. i installed openjdk-7, librxtx-java on my processor. my code and error is below. If any have idea or solution then please suggest to me.
package serialcomm_linaro;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TwoWaySerialComm
{
public TwoWaySerialComm()
{
super();
}
void connect ( String portName ) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
(new Thread(new SerialReader(in))).start();
(new Thread(new SerialWriter(out))).start();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
/** */
public static class SerialReader implements Runnable
{
InputStream in;
public SerialReader ( InputStream in )
{
this.in = in;
}
public void run ()
{
byte[] buffer = new byte[1024];
int len = -1;
try
{
while ( ( len = this.in.read(buffer)) > -1 )
{
System.out.print(new String(buffer,0,len));
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
/** */
public static class SerialWriter implements Runnable
{
OutputStream out;
public SerialWriter ( OutputStream out )
{
this.out = out;
}
public void run ()
{
try
{
int c = 0;
while ( ( c = System.in.read()) > -1 )
{
this.out.write(c);
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
public static void main ( String[] args )
{
try
{
(new TwoWaySerialComm()).connect("/dev/ttyS0");
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
my out is below . In this out i just send 123 and i get return back 23 first and then 1111... more time, and then errore. Instead of 111111.... i want only return back 123.
enter code here
RXTX Warning: Removing stale lock file. /var/lock/LCK..ttyS0
123
23
111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
java.io.IOExcepti on: Input/output error in nativeavailable
at gnu.io.RXTXPort.nativeavailable(Native Method)
at gnu.io.RXTXPort$SerialInputStream.read(RXTXPort.java:1429)
at gnu.io.RXTXPort$SerialInputStream.read(RXTXPort.java:1341)
at serialcomm_linaro.TwoWaySerialComm$SerialReader.run(TwoWaySerialComm.java:66)
at java.lang.Thread.run(Thread.java:722)
I hadn't tried serial communication over RXTX in a loopback scenario, but that shouldn't matter. The only thing that looks a bit suspicious is the part where you give the instance of the input stream to the SerialReader. I recommend that you pass SerialPort instance to both constructors, and every time you need to read from/write to the port's stream, use a stream getter, e.g. for reading:
public static class SerialReader implements Runnable
{
SerialPort serialPort;
public SerialReader ( SerialPort serialPort )
{
this.serialPort = serialPort;
}
public void run ()
{
byte[] buffer = new byte[1024];
int len = -1;
try
{
while ( ( len = serialPort.getInputStream().read(buffer)) > -1 )
{
System.out.print(new String(buffer,0,len));
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
please feedback.
UPDATE:
From my personal experience RXTX is a buggy solution. This however does not mean that this situation is caused by an underlying RXTX bug. It might be because the serial port isn't setup correctly, but in your case it is a standard port name with standard connection parameters. As a loooong shot, try replacing the baudrate 115200 with 9600, but that probably won't help. I can offer three paths from here:
try debugging the RXTX code - you might get more insight on what's happening
read the serial line troubleshooting
consider other Java solutions for serial communication, like JSSC instead of RXTX.
UPDATE:
I'm afraid I have been inattentive and jumped ahead. JSSC native libraries (.so,.dll) are inside the jssc.jar so they are loaded "automatically". With RXTX they come outside the jar file so you need to set the java.library.path system property in order for the JVM to find and load them or you'll get an UnsatisfiedLinkError.
You can open the JSSC jar file by a double click, and it will open in an archiver because it is actually a zip file. As with RXTX, you will notice that the native libs files are organized in directories named like operating systems (windows, linux, RXTX has Mac_OS_X and Solaris also).
Inside these directories there are the native libs files, the .so, dll., and .jnilib types of files, which are named after computer architectures. That's the broader meaning of the word, these are short codes for instruction set architectures (ISA). The instruction set defines the set of instructions (commands) for a CPU. In other words, there are many different CPU models (like your AllWinner A13) that conform to the same instruction set. The native libs source code is compiled to produce the executables (.so,...) which is a bunch of instructions from that same instruction set.
The reason why you got the UnsatisfiedLinkError with JSSC might be because you're on an unsupported architecture, and the corresponding native lib is being is searched for in an unexistent directory. The ISA short codes, which are also the names of these directories for JSSC are x86 and PPC architectures, both 32 and 64 bit variant. RXTX has many other's but I think that none of them is equivalent to ARMv7 which is the ISA of your AllWinner A13 CPU.
You can determine your architecture by executing this command in terminal:
uname -m
On my linux it ouputs:
x86_64
which means that it is a 64bit Intel 8086 architecture. Both JSSC and RXTX have implemented this architecture. If your architecture isn't implemented (supported) than you can't use these libraries to connect to serial port on that computer. In that case you must write your own or obtain a suitable implementation.
If the architecture matches and there are still native errors you might try recompiling the native libs sources. The sources are provided for both RXTX and JSSC.
UPDATE:
If your architecture is armv7l that means that JSSC, RXTX and JavaComm (approximatley said, RXTX "ancestor") in their current state are useless in your scenario.
I didn't manage to find any other open source java library for serial communication. If that is really true, you'd need to write your own native library conforming to the interface of the one of the above libraries to make them useful. In other words, you'd need to write a C program (something like this: 1, 2) with functionality of serial communication and JNI interface to the Java library.
In the sense of the answer completness, I'll mention a commercial product SerialIO which does support some ARM architectures (don't know if your is one of them). But if you decide for that solution, you can always send a query to their support.
I've checked the other answers and they didn't help me with this error. Maybe I'm doing something else wrong.
Here's my code:
void uploadPic() throws FileNotFoundException
{
FileInputStream fis = new FileInputStream(path);
FTPClient con = new FTPClient();
int bytesAvailable;
try
{
con.connect("ftp://ftp.drivehq.com/");
Toast.makeText(this, "Connected to FTP", Toast.LENGTH_SHORT).show();
if (con.login("x", "x"))
{
Toast.makeText(this, "Logged in", Toast.LENGTH_SHORT).show();
con.enterLocalPassiveMode(); // Active mode doesn't really work on Android
bytesAvailable = fis.available();
byte[] barray = new byte[bytesAvailable];
fis.read(barray);
ByteArrayInputStream in = new ByteArrayInputStream(barray);
boolean result = con.storeFile("/CameraUpload.jpg", in);
in.close();
if (result) Log.v("Upload Result", "Succeeded");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
I've added INTERNET permission to my project.
The logcat shows these errors:
android.os.NetworkOnMainThreadException
W/System.err(17531): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
W/System.err(17531): at java.net.InetAddress.lookupHostByName(InetAddress.java:391
I'm connected to the internet via Wifi.
That exception seems to be thrown when you try to perform network operations (such as FTP) from your main thread. This is not allowed for performance reasons (so that the application doesn't appear to lock up to the user, when performing an action which may take a while). Assuming you are using Honeycomb or higher, you would need to move the code that makes the connection into its own child thread.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
http://developer.android.com/guide/practices/design/responsiveness.html
Most likely, this error means that your device cannot resolve ftp.drivehq.com to its IP address. I can't say for sure because you only pasted part of the error log. Make sure you have network connection and that your DNS is working correctly. See if you can connect to this same site via android browser, for example.
Hi i'm begginer in java,in my project datalogger is connected to com port i have to send 15 integer value to port then other device will send back 15 as a response,now i'm writing to outputstream but i'm not getting response.how to solve this problem plz help me.(i'm using javax.com package)
thanks for reply
You have to get an InputStream as well, you can't read from the OutputStream. Or am I missing something?
Also, remember to do OutputStream.flush() after writing your output, otherwise your data might be buffered to be sent later - if the responder is waiting for your data, this is most likely where things goes wrong.
Having said that: the javax.comm package is really old. Last time I worked with it, it almost seemed deprecated by Sun, or at least not maintained in any way. You might want to look at other solutions (SerialIO comes to mind).
Try following sample code
public static void init(String port) {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
System.out.println(portId.getName());
if (portId.getName().equals(port)) {
try {sPort = (SerialPort) portId.open("PORT_NAME", 2000);
reader = new sms();
break;
}
catch (Exception e) { System.out.println(e);continue;}
}
}
}
and call init() method with com port name (like COM15,COM11,COM12 etc..) check your device com port to which it is connected.