I want to download a file in java application and when I try it, it creates the file on my hard drive but then fails to download it completely. I am using the ftp4j library to do it.
import it.sauronsoftware.ftp4j.*;
public class Main {
public static void main (String args[]){
FTPClient client = new FTPClient();
try{
client.connect("ftp.myaddress.comlu.com");
client.login("username", "password");
System.out.println("Connection created");
client.download("public_html/ZScreen.png", new java.io.File("d:/xxx/ZScreen.png"));
System.out.println("Download successful");
client.disconnect(true);
}
catch (Exception FTPException){
System.out.println("Shit hit the fan");
}
}
}
I always get the Connection created and Shit hit the fan. Also, there is a file created on my hard drive but it's size is 0 bytes.
This is the stack race
Connection created
java.net.SocketException: Connection reset
Shit hit the fan
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
at sun.nio.cs.StreamDecoder.read0(StreamDecoder.java:126)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:112)
at java.io.InputStreamReader.read(InputStreamReader.java:168)
at it.sauronsoftware.ftp4j.NVTASCIIReader.readLine(NVTASCIIReader.java:105)
at it.sauronsoftware.ftp4j.FTPCommunicationChannel.read(FTPCommunicationChannel.java:142)
at it.sauronsoftware.ftp4j.FTPCommunicationChannel.readFTPReply(FTPCommunicationChannel.java:187)
at it.sauronsoftware.ftp4j.FTPClient.openPassiveDataTransferChannel(FTPClient.java:3538)
at it.sauronsoftware.ftp4j.FTPClient.openDataTransferChannel(FTPClient.java:3473)
at it.sauronsoftware.ftp4j.FTPClient.download(FTPClient.java:3302)
at it.sauronsoftware.ftp4j.FTPClient.download(FTPClient.java:3213)
at it.sauronsoftware.ftp4j.FTPClient.download(FTPClient.java:3078)
at Main.main(Main.java:9)
Apparently there is a bug on the Windows 7 firewall related to using FTP on IPv6 that would explain your problem. See bug report here.
Any one of the following workarounds should suffice to fix it:
Run the following as an administrator in a Windows console:
netsh advfirewall set global StatefulFtp disable
Run the JVM with the option: -Djava.net.preferIPv4Stack=true
You do not have the rights to write on the folder. Check if the repertory is not under "read-only" state.
Related
I am learning Java and trying to put together a simple App containing a few jTables connected to database that can be updated etc. To do this I have created a database with a few tables through Netbeans which I understand (and wish) to be embedded in the final distributable app.
I am following the Programming Knowledge tutorials on Youtube to create most of the GUI. Everting is OK as long as I open the Services tab on Netbeans and manually right-click my database(testDB) and click Start Server. Then when I run the following code I get a successful connection:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
//Register JDBC driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
//Open a connection
String DB_URL = "jdbc:derby://localhost:1527/testDB";
String u_name = jTextField1.getText();
String p_word = jPasswordField1.getText();
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/testDB",u_name,p_word);
JOptionPane.showMessageDialog(null,"Details Correct - Connection established");
Close_me();
Open_Table_GUI(u_name,p_word);
}
catch(ClassNotFoundException | SQLException e){
System.out.println(e);
}
}
However if I run that code WITHOUT manually clicking on start server I get the following:
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused.
I have read the apache documentation and due to my level of inexperience I am not getting anywhere.
I have also checked out the answers to similar connection questions on here but again I can't seem to relate the issue in a way that works.
The ultimate goal for me is to have an app I can distribute to run on windows machines that will have the database/tables all included individually editable etc. I would hope to eventually create a database that resides on a shared drive and each individual can connect to automatically - but that's way down the line for now.
My request here is that someone can help me understand what I need to change in my code so that the "Start Server" is automatically done.
Thanks in advance for nay response.
OK guys so I found code that seems to work for me from a question asked on here by LMS
private void setup(){
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection=DriverManager.getConnection("jdbc:derby:sheet;create=true","test","1234");
statement=connection.createStatement();
}
catch(ClassNotFoundException cnf){
System.out.println("class error");
}
catch(SQLException se){
System.out.println(se);
}
}
If anyone cares to link me to a reason why this in fact works that would be great, I'm assuming the Embedded driver doesn't go through the port and just looks within the project??
Anyway initially this seems to be solved!!
Please check your Server setting i.e.
-username and pwd in your program
and check that did you start the Derby server and is it listening at port 1527?
I have a large java application (which is used to generate some type of report) in which below class is used to create datasource.
import org.apache.log4j.Logger;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import com.mysql.jdbc.Connection;
public class DatabaseConnection
{
private static final Logger LOGGER = Logger.getLogger(DatabaseConnection.class.getName());
#SuppressWarnings("deprecation")
public static DriverManagerDataSource jdbcConnection(WebmartConfiguration webmartconnection)
{
DriverManagerDataSource dataSource = null;
try
{
dataSource = new DriverManagerDataSource("com.mysql.jdbc.Driver", "jdbc:mysql://" + webmartconnection.getHostname() + ":" + webmartconnection.getPort() + "/" + webmartconnection.getDatabasename() + "", webmartconnection.getUsername(), webmartconnection.getPassword());
}
catch (Exception sqle)
{
LOGGER.info(sqle);
}
return dataSource;
}
}
and that datasource is passed to many method that are used to execute query using JDBCTEMPLATE's query method. For some time application runs smooth and generate reports but after some time application terminated with following stacktrace.
ERROR [run has started] (DivisionThread.java:217) - Could not get JDBC Connection; nested exception is com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: java.net.SocketException: Too many open files
STACKTRACE:
java.net.SocketException: java.net.SocketException: Too many open files
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2641)
at com.mysql.jdbc.Connection.<init>(Connection.java:1531)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:190)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:173)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:164)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:149)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:119)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:573)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:637)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:666)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:674)
at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:729)
at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:745)
at com.mpsinsight.reporting.dao.common.CommonUtilReport.getOutFileName(CommonUtilReport.java:1509)
at com.mpsinsight.reporting.bean.common.ActionEnum$9.getparameterType(ActionEnum.java:507)
at com.mpsinsight.reporting.main.common.JasperReport.populateParameters(JasperReport.java:142)
at com.mpsinsight.reporting.main.common.JasperReport.generateReport(JasperReport.java:61)
at com.mpsinsight.reporting.main.common.GenerateReport$4.generateReport(GenerateReport.java:123)
at com.mpsinsight.reporting.main.common.DivisionThread.run(DivisionThread.java:179)
** END NESTED EXCEPTION **
Example :
Below is the one of the method of application that uses datasource.
public String getOutFileName(DriverManagerDataSource datasource, WebmartConfiguration webmartconnection, String abbrev)
{
DriverManagerDataSource dmDatasource = null;
dmDatasource = datasource;
if (dmDatasource == null)
{
dmDatasource = DatabaseConnection.jdbcConnection(webmartconnection);
}
JdbcTemplate jdbcTemplateOb = new JdbcTemplate(dmDatasource);
String sql = QueryList.Value("outFileNameQuery");
LOGGER.info("abbrev :::: " + abbrev);
LOGGER.info("outFileNameQuery :::: " + sql);
String pathname = (String) jdbcTemplateOb.queryForObject(sql, new Object[] { abbrev }, String.class);
LOGGER.info("pathname :::: " + pathname);
return pathname;
}
Could someone explain what could the reason for too many open files error and how can i resolve it.
EDIT :
I am working on linux environment. The above error occur only in linux environment.
Check open file limit using below linux command.
ulimit -a
and you can provide open file limit in below file through root user.
/etc/security/limits.conf
For example
{username} soft nofile 1024
{username} hard nofile 65536
The reason for a "too many open files" is that the application or system is reaching the limit of allowed file handles.
This problem usually occurs after several concurrent users get a connection to the Server. Java opens many files in order to read in the classes required to run your application. High volume applications can use a lot of file descriptors. This could lead to a lack of new file descriptors. Also, each new socket requires a descriptor. Clients and Servers communicate via TCP sockets. Each browser's http request consumes TCP sockets when a connection is established to a Server.
In order to prevent a file descriptor leak you should ensure that all resources like streams, database connections are explicitly closed as soon as they are no longer needed. Even Java manages resources for you: don't rely on the garbage collector to clean up your used resources. i.e. close all streams either within a finally block or use the Java 7 try with resources syntax.
The reason for the limit is that the operating system needs memory to manage manage each open file, and memory is a limited resource. Different platforms have different limits on the number of files that can be open in a single process at one time.
On Linux you can as root user change the maximum of the open files count per process (via ulimit -n) and per system (e.g. echo 800000 > /proc/sys/fs/file-max) or per user
using the /etc/security/limits.conf file. For the last option you may need a special user running your application.
Before you change one or more of these values you should check whether your application has a resource leak by monitoring the open files. One possible option on Linux is to use
strace.
strace -e trace=open,close,read,write,connect,accept your-command-here
You'll need to use the -o option to put strace's output somewhere other than the console, if the process can print to stderr. If your process forks, you'll also need -f or -ff
Or if you want to connect you to a running process and you know the process id you can use strace -p $MyProcess.
If you search the web you'll find a solution for monitoring the open file descriptors that matches your needs. For example monitor open process files on linux (real-time)
I have been unable to find a solution that fixes my issue, so I am opening a new topic.
Utgard (http://openscada.org/projects/utgard) seems like a very useful tool to me. In this phase I just want to be able to access the TOP OPC Server locally on a Windows 8 OS via Eclipse. However, when trying to run their tutorial I end up with an "Access is denied". I do not think that I have made any mistakes with username, password and so on.
The Exele OPC DA Test Client does not return any errors. I can connect, retrieve and rewrite values.
Please note that I am a newbie when it comes to OPC and OpenSCADA. Any help will be greatly appreciated.
package org.openscada.opc.tutorial;
import java.util.concurrent.Executors;
import org.jinterop.dcom.common.JIException;
import org.openscada.opc.lib.common.ConnectionInformation;
import org.openscada.opc.lib.da.AccessBase;
import org.openscada.opc.lib.da.DataCallback;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.ItemState;
import org.openscada.opc.lib.da.Server;
import org.openscada.opc.lib.da.SyncAccess;
public class UtgardTutorial1 {
public static void main(String[] args) throws Exception {
// create connection information
final ConnectionInformation ci = new ConnectionInformation();
//final ConnectionInformation connectionInformation = new ConnectionInformation();
ci.setHost("127.0.0.1");
//ci.setDomain("");
ci.setUser("Me");
ci.setPassword("Password");
ci.setProgId("SWToolbox.TOPServer.V5");
//ci.setClsid("680DFBF7-C92D-484D-84BE-06DC3DECCD68"); // if ProgId is not working, try it using the Clsid instead
// create an id for the tag you want to retrieve
final String itemId = "_System._Time_Second";
// create a new server
final Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor());
//final Server serverServer = new Server(connectionInformation, Executor.newSingleThreadSchedulesExecutor);
try {
// connect to server
server.connect();
// add sync access, poll every 500 ms
final AccessBase access = new SyncAccess(server, 500);
access.addItem(itemId, new DataCallback() {
#Override
public void changed(Item item, ItemState state) {
System.out.println(state);
}
});
// start reading
access.bind();
// wait a little bit
Thread.sleep(10 * 1000);
// stop reading
access.unbind();
} catch (final JIException e) {
System.out.println(String.format("%08X: %s", e.getErrorCode(), server.getErrorMessage(e.getErrorCode())));
}
}
}
Error stack trace:
INFO org.openscada.opc.lib.da.Server - Failed to connect to server
org.jinterop.dcom.common.JIException: Access is denied, please check whether the [domain-username-password] are correct. Also, if not already done please check the GETTING STARTED and FAQ sections in readme.htm. They provide information on how to correctly configure the Windows machine for DCOM access, so as to avoid such exceptions. [0x00000005]
at org.jinterop.winreg.smb.JIWinRegStub.winreg_OpenKey(Unknown Source) ~[org.openscada.jinterop.core_2.0.8.201303051454.jar:na]
at org.jinterop.dcom.core.JIProgId.getIdFromWinReg(Unknown Source) ~[org.openscada.jinterop.core_2.0.8.201303051454.jar:na]
at org.jinterop.dcom.core.JIProgId.getCorrespondingCLSID(Unknown Source) ~[org.openscada.jinterop.core_2.0.8.201303051454.jar:na]
at org.jinterop.dcom.core.JIComServer.<init>(Unknown Source) ~[org.openscada.jinterop.core_2.0.8.201303051454.jar:na]
at org.openscada.opc.lib.da.Server.connect(Server.java:123) ~[org.openscada.opc.lib_1.0.0.201303051455.jar:na]
at org.openscada.opc.tutorial.UtgardTutorial1.main(UtgardTutorial1.java:32) [bin/:na]
Caused by: org.jinterop.dcom.common.JIRuntimeException: Access is denied, please check whether the [domain-username-password] are correct. Also, if not already done please check the GETTING STARTED and FAQ sections in readme.htm. They provide information on how to correctly configure the Windows machine for DCOM access, so as to avoid such exceptions. [0x00000005]
at org.jinterop.winreg.IJIWinReg$openKey.read(Unknown Source) ~[org.openscada.jinterop.core_2.0.8.201303051454.jar:na]
at ndr.NdrObject.decode(Unknown Source) ~[org.openscada.jinterop.deps_1.0.0.201303051454.jar:na]
at rpc.ConnectionOrientedEndpoint.call(Unknown Source) ~[org.openscada.jinterop.deps_1.0.0.201303051454.jar:na]
at rpc.Stub.call(Unknown Source) ~[org.openscada.jinterop.deps_1.0.0.201303051454.jar:na]
You don't have access to the local Windows Registry, so the client fails to convert the server's ProgID to CLSID. Make sure you run the application with enough privileges in there, i.e. that you are an Administrator user.
Alternatively, you can just configure the connection using the server's CLSID, so you will not need the registry.
An OPC client should actually use the OpcEnum service running on the server computer to do the ProgID to CLSID conversion. Perhaps the service is not available or Utgard only tries the registry (I do not know Utgard myself). If you don't have the server installed on the client machine, the registry-based ProgID to CLSID conversion will fail anyway, since that information is not available in the local Windows Registry. The worst case is that Utgard will try to open the remote Windows Registry, which only rarely succeeds (or you need to ensure that it's enabled separately).
Note that as I do not know Utgard, I am just guessing which strategies it is attempting. Nevertheless, using CLSID only will bypass the whole conversion part, which is your problem.
E: Considering that your other client can connect without a problem, I suspect that Utgard does not try to use OpcEnum at all.
I got the same error, and solve the problem by
applying the following patch to the registry:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
create or modify 32-bit DWORD: LocalAccountTokenFilterPolicy
set the value to: 1
I'm trying to upload a simple txt file via FTP using XAMPP and FileZilla.
I'm using the Apache Commons Net 3.0.1 Library.
This is my code, very basic things:
FTPClient client = new FTPClient();
InputStream in = new ByteArrayInputStream("IT WORKS! :D".getBytes());
try {
client.connect("localhost");
client.login("user", "password");
client.enterLocalPassiveMode();
client.storeFile("textfile.txt", in);
} finally {
try {
in.close();
client.logout();
client.disconnect();
} catch (Exception e) {
}
}
But... storeFile() throws a java.net.SocketException:
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:154)
at java.io.BufferedReader.read(BufferedReader.java:175)
at org.apache.commons.net.io.CRLFLineReader.readLine(CRLFLineReader.java:58)
at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:310)
at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:290)
at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:474)
at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:547)
at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:596)
at org.apache.commons.net.ftp.FTP.pasv(FTP.java:945)
at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:719)
at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:551)
at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:1704)
at ftpexample.ftpexample.main(ftpprova.java:17)
What's the problem?? :(
I tried also on an online hosting service, with the same result...
I wonder if this is a firewall or windows' services related problem??
Solved by running this as administrator in the command prompt:
netsh advfirewall set global StatefulFTP disable
This is a Java 7 bug on Windows machines, it is reported here.
Set:
client.setUseEPSVwithIPv4( true );
This works if you can't make changes to Window's firewall settings.
I'm honestly not sure but you should try the following:
Use something like the following code:
System.out.println(client.getReplyCode());
for(String s : client.getReplyStrings())
System.out.println(s);
after client.login("user", "password"); to verify the status of your connection.
If you don't get any good hints from the code above, after invoking client.storeFile("textfile.txt", in); try to add client.completePendingCommand();.
Good luck! :)
I want to check the existence of a url and i tried with the following code in java,
public boolean exists(String URLName) {
try {
if (!URLName.toUpperCase().contains("HTTP"))
URLName="http://"+URLName;
URL url = new URL(URLName);
System.setProperty("java.net.useSystemProxies", "true");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(9000);
urlConn.setReadTimeout(9000);
urlConn.connect();
if(HttpURLConnection.HTTP_OK == urlConn.getResponseCode())
return true;
else
return false;
}
catch (SocketTimeoutException e){
return false;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
The above code is working fine in windows but when the code is run through server (linux) i am getting the following error message,
GConf Error: Failed to contact configuration server; some possible
causes are that you need to enable TCP/IP networking for ORBit, or
you have stale NFS locks due to a system crash. See
http://projects.gnome.org/gconf/ for information. (Details - 1:
Not running within active session)
GConf Error: Failed to contact configuration server; some possible
causes are that you need to enable TCP/IP networking for ORBit, or
you have stale NFS locks due to a system crash. See
http://projects.gnome.org/gconf/ for information. (Details - 1:
Not running within active session)
java.net.UnknownHostException: www.ep.gov
at
java.net.PlainSocketImpl.connect(PlainSocketImpl.j ava:177)
at
java.net.SocksSocketImpl.connect(SocksSocketImpl.j ava:366)
at java.net.Socket.connect(Socket.java:525)
at sun.net.NetworkClient.doConnect(NetworkClient.java :158)
at
sun.net.http://www.http.HttpClient.openServe...lient.java:394)
at
sun.net.http://www.http.HttpClient.openServe...lient.java:529)
at sun.net.www.http.HttpClient.<init>(HttpClient.java :233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:323)
at
sun.net.http://www.protocol.http.HttpURLConn...ction.java:860)
at
sun.net.http://www.protocol.http.HttpURLConn...ction.java:801)
at
sun.net.http://www.protocol.http.HttpURLConn...ction.java:726)
I got the below message from server admin
It is working, while it was run in X session (GUI Mode).
But it is not working in non-GUI mode. Please try to change the coding to make use of non-GUI mode." It seems the above code is making use of GUI mode.
I need an alternate code to check url existence without using GUI.
Regards
Linda
UnknownHostException means that the request is not reaching to its destination. There could be many reason that the linux server is unreachable to the desired URL www.ep.gov.
Please make sure that the server can reach the URL www.ep.gov.
I think your problem is with this line:
System.setProperty("java.net.useSystemProxies", "true");
It seems this causes the system to try and find the HTTP proxy configuration for the web browser, and ends up running into some problems with the Gnome configuration.
Do you actually need to use a HTTP proxy? If not, simply remove that line. If you do, read this page to learn how to configure proxies.