I am sure that I am using the correct connection information:
import com.bmc.arsys.api.ARException;
import com.bmc.arsys.api.ARServerUser;
/**
*
* A class to automate deletion of BMC Remedy incidents after deploying or decommissioning servers
*
*/
#SuppressWarnings("unused")
public class BMCIncidentDelete {
public static void main(String[] args) {
/*
* Authentication information
*/
String host = "";
String server = "";
String user = "";
String pass = "";
ARServerUser ctx = new ARServerUser();
ctx.setServer(host);
// ctx.setServer(server);
ctx.setUser(user);
ctx.setPassword(pass);
ctx.setPort(8080);
/*
* Verify user or print stack trace if not possible
*/
try {
ctx.verifyUser();
System.out.println("Connection verified!");
} catch (ARException e) {
System.out.println(e.getMessage().toString());
}
}
}
Unfortunately, I get the following error:
ERROR (90): Cannot establish a network connection to the AR System server; Connection refused: connect
Anyone with experience with the AR System API see this issue before? https://communities.bmc.com/docs/DOC-17514
This error (Connection refused) indicates that the Remedy server is not reachable from your server on the host and port provided. You can validate by using telnet, substituting the hostname for $host:
$ telnet $host 8080
A successful connection should say "Connected to host.", but based on your question you will likely see "Connection refused". Double check the hostname and port number of the Remedy server, and if necessary check that there are no firewalls, etc. between you and the server.
Related
I'm trying to use racer (Description Logic reasoner), but i get the following error
com.racersystems.jracer.RacerClientException: Connection refused: connect
at com.racersystems.jracer.RacerClient.openConnection(RacerClient.java:76)
at test.Test.main(Test.java:12)
the code i'm executing is the following :
package test;
import com.racersystems.jracer.*;
public class Test {
public static void main(String[] argv) {
String ip = "127.0.0.1";
int port = 8088;
String filename="\"/jracer-2-0.zip_expanded/jracer-2-0/demo/people+pets.owl\"";
RacerClient racer = new RacerClient(ip,port);
try {
racer.openConnection();
System.out.println(racer.sendRaw("(owl-read-file " + filename + ")"));
System.out.println(racer.sendRaw("(all-atomic-concepts)"));
racer.closeConnection();
}
catch (Exception e) {
e.printStackTrace();
}
}}
I don't know who to solve it ?
Any suggestions ?
You are apparently trying to connect to a service that is running on the same machine as you are running the program ... using the 127.0.0.1 loopback interface.
The fact that it is giving you a "connection refused" response means that the service is not currently running on "this machine" or the port that you have specified.
The solution will be to ensure that the service is running and listening on the specified IP and port; e.g. check the IP address and port, and start or restart the service.
I'm working with FTPClient against an FTP server using Testcontainers.
A reproducible code sample is here:
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.images.builder.ImageFromDockerfile;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import static org.assertj.core.api.Assertions.assertThat;
#Testcontainers
class FtpUtilsTest {
private static final int PORT = 21;
private static final String USER = "user";
private static final String PASSWORD = "password";
private static final int FTP_TIMEOUT_IN_MILLISECONDS = 1000 * 60;
private static final GenericContainer ftp = new GenericContainer(
new ImageFromDockerfile()
.withDockerfileFromBuilder(builder ->
builder
.from("delfer/alpine-ftp-server:latest")
.build()
)
)
.withExposedPorts(PORT)
.withEnv("USERS", USER + "|" + PASSWORD);
#BeforeAll
public static void staticSetup() throws IOException {
ftp.start();
}
#AfterAll
static void afterAll() {
ftp.stop();
}
#Test
void test() throws IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.setDataTimeout(FTP_TIMEOUT_IN_MILLISECONDS);
ftpClient.setConnectTimeout(FTP_TIMEOUT_IN_MILLISECONDS);
ftpClient.setDefaultTimeout(FTP_TIMEOUT_IN_MILLISECONDS);
// Log
ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
// Connect
try {
ftpClient.connect("localhost", ftp.getMappedPort(PORT));
ftpClient.setSoTimeout(FTP_TIMEOUT_IN_MILLISECONDS);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
throw new AssertionError();
}
// Login
boolean loginSuccess = ftpClient.login(USER, PASSWORD);
if (!loginSuccess) {
throw new AssertionError();
}
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
} catch (IOException e) {
throw new AssertionError(e);
}
String remoteFile = "fileonftp";
try (InputStream targetStream = new ByteArrayInputStream("Hello FTP".getBytes())) {
assertThat(ftpClient.isConnected()).isTrue();
ftpClient.storeFile(remoteFile, targetStream);
}
}
}
This prints:
220 Welcome Alpine ftp server https://hub.docker.com/r/delfer/alpine-ftp-server/
USER *******
331 Please specify the password.
PASS *******
230 Login successful.
TYPE I
200 Switching to Binary mode.
PASV
227 Entering Passive Mode (172,17,0,3,82,15).
[Replacing PASV mode reply address 172.17.0.3 with 127.0.0.1]
then fails with:
Connection refused (Connection refused)
java.net.ConnectException: Connection refused (Connection refused)
...
at java.base/java.net.Socket.connect(Socket.java:609)
at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:866)
at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:1053)
at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:3816)
at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:3846)
What I don't understand is that it fails after successfully connecting and logging in, and returning true for isConnected.
Turns out that when removing the ftpClient.enterLocalPassiveMode(); it works, but I need it to work with the passive mode.
I guess the failure is related when switching to a different port for the passive call.
but when trying to add the ports to the withExposedPorts the container fails to start with:
Caused by: org.testcontainers.containers.ContainerLaunchException: Timed out waiting for container port to open (localhost ports: [55600, 55601, 55602, 55603, 55604, 55605, 55606, 55607, 55608, 55609, 55598, 55599] should be listening)
Running against a docker (docker run -d -p 21:21 -p 21000-21010:21000-21010 -e USERS="user|password" delfer/alpine-ftp-server) works.
Local docker versions:
Docker version 20.10.11, build dea9396
Docker Desktop 4.3.1
Testcontainers - appears to behave the same both on 1.16.2 and 1.15.3
Link to testcontainers discussion
As you already figured out in the comments, the tricky part about FTP passive mode is that the server uses another port (not 21) for communication.
In the docker image you're using, it's a port from the 21000-21010 range by default. So you need to publish (expose) these additional container ports. In docker run command you used -p 21000-21010:21000-21010 for that.
However, Testcontainers library is designed to publish to random host ports to avoid the problem, when a desired fixed port (or a range of ports) is already occupied on the host side.
In case of FTP passive mode random ports on the host side cause problems, because afaik you can't instruct the ftp client to override the port, which FTP server returned for the passive mode. You'd need something like ftpClient.connect("localhost", ftp.getMappedPort(PORT)); but for passive mode ports as well.
Therefore the only solution I see here is to use a FixedHostPortContainer. Even though it's marked as deprecated and not recommended to use because of the mentioned issues with occupied ports, I think this is a valid use case for it here. FixedHostPortGenericContainer allows to publish fixed ports on the host side. Something like:
private static final int PASSIVE_MODE_PORT = 21000;
...
private static final FixedHostPortGenericContainer ftp = new FixedHostPortGenericContainer<>(
"delfer/alpine-ftp-server:latest")
.withFixedExposedPort(PASSIVE_MODE_PORT, PASSIVE_MODE_PORT)
.withExposedPorts(PORT)
.withEnv("USERS", USER + "|" + PASSWORD)
.withEnv("MIN_PORT", String.valueOf(PASSIVE_MODE_PORT))
.withEnv("MAX_PORT", String.valueOf(PASSIVE_MODE_PORT));
Keep in mind that this solution relies on the assumption that 21000 port is always free. If you're going to run this in the environment where it's not guaranteed, then you need to tweak it to find a free host port first. Like:
private static FixedHostPortGenericContainer ftp = new FixedHostPortGenericContainer<>(
"delfer/alpine-ftp-server:latest")
.withExposedPorts(PORT)
.withEnv("USERS", USER + "|" + PASSWORD);
#BeforeAll
public static void staticSetup() throws Exception {
Integer freePort = 0;
try (ServerSocket socket = new ServerSocket(0)) {
freePort = socket.getLocalPort();
}
ftp = (FixedHostPortGenericContainer)ftp.withFixedExposedPort(freePort, freePort)
.withEnv("MIN_PORT", String.valueOf(freePort))
.withEnv("MAX_PORT", String.valueOf(freePort));
ftp.start();
}
An answer similar to the accepted one but without using deprecated functionalities.
Note that we still have to use the fixed port 21000.
public static class FTPContainer extends GenericContainer<FTPContainer>
{
private static FTPContainer container;
private FTPContainer()
{
super(DockerImageName.parse("delfer/alpine-ftp-server:latest"));
}
#SuppressWarnings("resource")
public static FTPContainer getInstance()
{
if (container == null)
{
container = new FTPContainer().withEnv("USERS", "test|test|/home/").withExposedPorts(21)
.withCreateContainerCmdModifier(e -> e.getHostConfig()
.withPortBindings(new PortBinding(Ports.Binding.bindPort(21000), new ExposedPort(21000))))
.withEnv("MIN_PORT", "21000").withEnv("MAX_PORT", "21000");
}
return container;
}
#Override
public void start()
{
super.start();
}
#Override
public void stop()
{
// Handled when JVM stops
}
}
And then you can use your FTP server instance like
FTPContainer FTP = FTPContainer.getInstance();
FTP.start();
I am trying to connect to my database by JDBC on localhost. Connecting via windows authentication is no problem, but I want to connect via SQL authentication. Therefore, I created a login and a user corresponding to this login in my database. I can normally log in SSMS:
My connection string for JDBC:
jdbc:sqlserver://localhost:1433;databaseName=TestBazyDanych;user=doszke;password=doszke123
Thrown exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'doszke'. ClientConnectionId:b7005fe3-904d-40c5-a89e-af0cb61250d6
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:254)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:258)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:104)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:4772)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3581)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:81)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3541)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7240)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2869)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2395)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2042)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1889)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1120)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:700)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:251)
at main.Main.main(Main.java:38)
The username and password are the same, as those used for loging to SSMS.
Here my class code:
package main;
import java.sql.*;
public class Main {
private static ResultSet selectStan(Connection connection) throws SQLException {
String sql_stmt = "SELECT * FROM STAN;";
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql_stmt);
System.out.println("Select executed");
return result;
}
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String userName = "doszke";
String password = "doszke123";
String url = "jdbc:sqlserver://localhost:1433;databaseName=TestBazyDanych;user=doszke;password=doszke123";
try (Connection con = DriverManager.getConnection(url)) {
if(con != null){
System.out.println("connected");
} else {
System.out.println("unable to connect");
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
As Mark Rotteveel pointed out, I was trying to connect to a LocalDB instance with JDBC, which seemed undoable. (ref: here)
However, I installed jTDS and added to my classpath, changed my connection string to
jdbc:jtds:sqlserver://./TestBazyDanych;instance=LOCALDB#EB7165FD;namedPipe=true
create a connection by the use of this connection string, username and password and it worked. The instance pipe number was taken from cmd line via
sqllocaldb i MSSQLLocalDB
There are few things need to check:
Did you create doszke user under the database and SSMS?
Are you able to login with doszke/doszke123 credentials in SSMS?
Please check 1433 port are open or not in your inbound and outbound firewall.
Trying to telnet on localhost 1433. If it's getting failed change below setting:
Go to Configuration tools -> SQL Server Configuration Manager Select SQL Server Network Configuration -> Select protocol in the right side window enable tcp/ip and restart the services in services.
I'm trying to connect my local Java application to a remote mySQL server. I have shell access to the server and its mySQL, but no root access.
I attempted to implement some code I found online that seems to accomplish this goal. First I SSH into the server, and then I attempt to access the mySQL database. However, I get the following error:
Jul 09, 2014 2:20:06 PM [myClassName] connect
SEVERE: null, message from server: "Host '[remoteHost]' is not allowed to connect to this MySQL server"
I understand that mySQL by default disallows remote client access, but what I don't understand is that in this case it seems to be disallowing itself access to its own mySQL server. (i.e. ["remoteHost"] in the error message is the same host as the one that hosts the mySQL server I'm trying to access.)
The code template I'm using is below. I've left all the fields (user, pass, host, etc.) the same as on the template for the purposes of this question.
Do I need to ask my system administrator to give me special permissions? I have no trouble accessing the mySQL server through terminal. Thanks in advance everyone
Credit to The Kahimyang Project (http://kahimyang.info/kauswagan/code-blogs/1337/ssh-tunneling-with-java-a-database-connection-example).
import java.util.logging.Logger;
import com.jcraft.jsch.*;
import java.util.logging.Level;
public class MysqlManager {
// Logger
private final static Logger LOGGER =
Logger.getLogger(MysqlManager.class.getName());
public static void main(String args[]) {
MysqlManager mng = new MysqlManager ();
mng.connect();
}
public void connect() {
//
int assigned_port;
final int local_port=3309;
// Remote host and port
final int remote_port=3306;
final String remote_host="kahimyang.info";
try {
JSch jsch = new JSch();
// Create SSH session. Port 22 is your SSH port which
// is open in your firewall setup.
Session session = jsch.getSession("user", remote_host, 22);
session.setPassword("ssh_password");
// Additional SSH options. See your ssh_config manual for
// more options. Set options according to your requirements.
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("Compression", "yes");
config.put("ConnectionAttempts","2");
session.setConfig(config);
// Connect
session.connect();
// Create the tunnel through port forwarding.
// This is basically instructing jsch session to send
// data received from local_port in the local machine to
// remote_port of the remote_host
// assigned_port is the port assigned by jsch for use,
// it may not always be the same as
// local_port.
assigned_port = session.setPortForwardingL(local_port,
remote_host, remote_port);
} catch (JSchException e) {
LOGGER.log(Level.SEVERE, e.getMessage()); return;
}
if (assigned_port == 0) {
LOGGER.log(Level.SEVERE, "Port forwarding failed !");
return;
}
// Database access credintials. Make sure this user has
// "connect" access to this database;
// these may be initialized somewhere else in your code.
final String database_user="user";
final String database_password="password";
final String database = "database";
// Build the database connection URL.
StringBuilder url =
new StringBuilder("jdbc:mysql://localhost:");
// use assigned_port to establish database connection
url.append(assigned_port).append ("/").append(database).append ("?user=").
append(database_user).append ("&password=").
append (database_password);
try {
Class.forName(
"com.mysql.jdbc.Driver").newInstance();
java.sql.Connection connection =
java.sql.DriverManager.getConnection(url.toString());
java.sql.DatabaseMetaData metadata = connection.getMetaData();
// Get all the tables and views
String[] tableType = {"TABLE", "VIEW"};
java.sql.ResultSet tables = metadata.getTables(null, null, "%", tableType);
String tableName;
while (tables.next()) {
tableName = tables.getString(3);
// Get the columns from this table
java.sql.ResultSet columns =
metadata.getColumns(null, tableName, null, null);
String columnName;
int dataType;
while (columns.next()) {
columnName = columns.getString(4);
dataType = columns.getInt(5);
// Your actual task;
}
}
} catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
java.sql.SQLException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
}
}
}
To figure out if your problem is Java-related or not, you could try to telnet to the SQL server.
$ telnet localhost 3306
If you are not allowed to connect, you will receive an error message similar to yours.
To allow access, your system administrator needs to run something like this:
$ mysql -u root -p
Enter password:
mysql> use mysql
mysql> GRANT ALL ON *.* to root#'localhost' IDENTIFIED BY 'your-root-password';
mysql> FLUSH PRIVILEGES;
About your concern (SQL server disallowing access from localhost): access should only allowed, if it is really necessary. So if you have only remote SQL clients, there is no need to allow access from the host localhost.
I am writing a java code to connect with MS SQL Server 2005. MS SQL Server is on Remote server windows server 2003. I am trying the following code but i am unable to establish a connection:
import java.*;
public class Connect {
private java.sql.Connection con = null;
private final String url = "jdbc:sqlserver://";
private final String serverName="xxx.xxx.xxx.xxx";
private final String portNumber = "1433";
private final String databaseName="myDb";
private final String userName ="user1";
private final String password = "xxxx";
private final String selectMethod = "cursor";
// Constructor
public Connect() {}
private String getConnectionUrl() {
return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
}
private java.sql.Connection getConnection() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
if(con!=null) System.out.println("Connection Successful!");
} catch(Exception e) {
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
return con;
}
/*
Display the driver properties, database details
*/
public void displayDbProperties() {
System.out.println("Perform Operations ");
}
private void closeConnection() {
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Connect myDbTest = new Connect();
// myDbTest.displayDbProperties();
}
}
But I am getting following exceptions:
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host has failed. java.net.ConnectException: Connection refused: connect
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source)
Error Trace in getConnection() : The TCP/IP connection to the host has failed. java.net.ConnectException: Connection refused: connect
Error: No active Connection
I am not getting where is the problem in the above code or do i need to do some setting
to connect to remote server.
Please give me your valuable suggestion which can help me to overcome with this problem.
Make sure that your SQL Server is configured to use TCP/IP. Enable it from SQL Server's Network Utility app. Also check there that the SQL Server is using port 1433 (IP Addresses - IPAll - TCP Port).
Try to use "telnet <server_host> 1433". If it doesn't connect you will not be able to establish a connection.
IMHO "Connection refused" means your database server is not visible from your application server.
Check IP address and port.
Check database connectivity directly from your database server (to avoid firewalls).
Check database connectivity from your application server.
Hope this will help you
ALLOW THE CONNECTION FIRST IN WHICH PC YOUR SQL SERVER IS RUNNING...
GO TO CONTROL PANEL-->ADMIN. TOOLS--->Windows Firewall with Advanced Security-->Inbounded rules-->new rule-->select port radio button -->next-->enter port 3306-->click next -->finally give the rule name like conn any...click finish