I have wrote following code:
private static void startH2(){
Server server = null;
try {
server = Server.createTcpServer("-tcpAllowOthers").start();
Class.forName("org.h2.Driver");
Connection conn = DriverManager.
getConnection("jdbc:h2:tcp://localhost/~/test;MODE=PostgreSQL", "sa", "");
} catch (Exception e) {
LOG.error("Error while initialize", e);
}
System.out.println("finish");
}
public static void main(String [] args){
startH2();
}
I run my main method and see following situation:
Looks like Server.createTcpServer creates new non daemon thread.
but by url localhost:8082 I don't see h2 web console(actual result - ERR_CONNECTION_REFUSED)
How to fix this?
P.S.
I have noticed that by url
http://localhost:9092/
my browser downlods file with strange content:
if to decode this text I see following message:
Version mismatch, driver version is “0” but server version is “15”
I use h2 version 1.4.182
H2 contains multiple servers:
the TCP Server (for H2 JDBC clients),
the Web Server (for browsers, the H2 Console application), and
the PG Server (for PostgreSQL clients).
You have started the TCP Server. If you want to use a browser, you also need to start the Web Server:
private static void startH2(){
Server tcpServer = null;
Server webServer = null;
try {
tcpServer = Server.createTcpServer("-tcpAllowOthers").start();
System.out.println("TCP Server Port: " + tcpServer.getPort());
Class.forName("org.h2.Driver");
Connection conn = DriverManager.
getConnection("jdbc:h2:tcp://localhost/~/test22;MODE=PostgreSQL", "sa", "");
webServer = Server.createWebServer().start();
System.out.println("Web Server (H2Console) Port: " + webServer.getPort());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("finish");
}
Related
Im losing my mind, is there any clear documentation how to run java RMI between host and client remotly? i find in different forums, various puzzle pieces, but never, a from a to z guide, which scurity guidelines have to be followed etc, so that a RMI works. Well, if I run the server and client locally, it works.
Now, my low-level problem is that even if I set the external server address everywhere (?), in the error message it says that "localhost" has refused the connection.... Do you have any ideas?
Client:
try {
System.setProperty("java.rmi.server.hostname","42.155.241.914");
String name = "RemoteBookService";
String serverIP = "42.155.241.914"; // or localhost if client and server on same machine.
int serverPort = 1099;
Registry registry = LocateRegistry.getRegistry(serverIP, serverPort);
IRemoteService rs = (IRemoteService) registry.lookup(name);
Error:
java.rmi.ConnectException: Connection refused to host: localhost;
nested exception is:
java.net.ConnectException: Connection refused: connect
Server:
public static void main(String[] args) throws MalformedURLException, AlreadyBoundException {
try {
System.setProperty("java.rmi.server.hostname","42.155.241.914");
LocateRegistry.createRegistry(1099);
String name="//42.155.241.914/RemoteBookService";
RemoteService rs = new RemoteService();
Naming.bind(name, rs);
System.out.println("Service started");
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("could not start registry");
}
}
At first glance it looks like your server uses LocateRegistry.createRegistry(port); which implies own registry (same process) which you don't store to local variable, and then you call Naming.rebind(bind, rs) which implies use of a local registry (same host, other process) on the default port.
Try changing the lines on server to:
Registry registry = LocateRegistry.createRegistry(port);
...
// NOTE registry.rebind not called with name="//42.155.241.914/RemoteBookService"
registry.rebind("RemoteBookService", stub);
Hopefully this may get you to the next step, but there are plenty of ways this could have gone wrong so you might need to edit the question with more details.
I started a project in java with ActiveMQ 5.17.0.
Therefore I have downloaded ActiveMQ and opened my terminal from the folder bin and execute ./activemq start.
I received:
INFO: Loading '/Users/NAME/Downloads/apache-activemq-5.17.0//bin/env'
INFO: Using java '/usr/bin/java'
INFO: Starting - inspect logfiles specified in logging.properties and log4j.properties to get details
./activemq: line 343: [: : integer expression expected
INFO: pidfile created : '/Users/NAME/Downloads/apache-activemq-5.17.0//data/activemq.pid' (pid '3084')
As I have seen in other posts, this is the expected result.
A part of my Java Code is:
public static void main(String[] args) {
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:8161"); // ActiveMQ-specific
Connection con = null;
try {
con = factory.createConnection();
Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); // non-transacted session
Queue queue = session.createQueue("test.queue"); // only specifies queue name
MessageProducer producer = session.createProducer(queue);
Message msg = session.createTextMessage("hello queue"); // text message
producer.send(msg);
} catch (JMSException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close(); // free all resources
} catch (JMSException e) { /* Ignore */ }
}
}
}
As soon as I try to open the website https://localhost:8161/admin/admin I receive the response that Safari, Chrome, and Firefox do not get connection to localhost.
Anybody any suggestions what to do?
I have already tried to download again, different browsers, start and stop the server several times.
The URL for the admin UI should be http: http://localhost:8161/admin or http://127.0.0.1:8161/admin/
The script activemq fails parsing the output of java -version. Maybe set the line VERSION= to your java version (e.g. VERSION=17 for java 17) to check if that is the issue.
Your code sample shows that you are attempting to send messages to the Web UI URL vs the JMS protocol port.
Try changing your code to use port '61616':
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616); // ActiveMQ-specific
For the web browser access, try starting with the non-SSL url: http://localhost:8161/admin/admin instead of 'https'.
I've recently finished working on my first JavaFX app.
It connects with a MySQL database that is set up on a local server.
Before using the application I need to start the servers running using Xampp.
Now I want to finally pack my app into an .exe file and use it.
I'm a complete newbie when it comes to the servers and databases. My question is - what do I do to make my app connect with the database itself once the user opens it?
Do I need to switch from a local host server to a remote server that will not require starting it each time?
My JavaFX app connects with MySQL using JDBC.
private static String url = "jdbc:mysql://localhost:3306/Finance?useSSL=false&serverTimezone=UTC";
private static String login = "root";
private static String password = "";
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(url, login, password);
return connection;
}
You can test your connection with a method like this:
public boolean canConnect() {
try {
con = DriverManager.getConnection(url, login, password);
//executed only if no errors are thrown
return true;
} catch (SQLException e) {
e.printStackTrace();
//can't connect
return false;
} finally {
//close connection if it was successful
try {
if (con!=null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
by calling it in your main method, or in your first stage like this:
if (!canConnect()) {
//notify the user
//start xampp or check connection to local server
} //else proceed
If you want to deploy your application with Xampp, you need to make Xampp to autostart when pc boots up, so the user don't have to start it manually in each boot.
If you are wondering how to auto-start your MySQL service in Xampp, you can find it here.
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 using Netty to build a client-server network communication. Is it possible to find out to which app a client has connected to in case of success?
It's the following problem I try to solve: If a Tomcat Server is listening to port 8080 my client app successfully connects to the "server". Looks like it doesn't matter who is listening to the port.
How can I find out if my server app is currently started and listening to the port instead of e.g. Tomcat?
This is the connection code of the client:
public void run(){
//disconnectTest();
createBootstrap( new Bootstrap(), new NioEventLoopGroup(), true);
}
public void createBootstrap( Bootstrap b, EventLoopGroup eventLoop, boolean initialAttempt){
mWorkerGroup = eventLoop;
try {
b.group(mWorkerGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
.handler(new ClientChannelInitializer());
logger.info("Connecting client...");
b.connect(mHost, mPort)
.addListener( new ConnectionListener(this, initialAttempt));
} catch (Exception e) {
logger.error("Failed to connect client to server '" +mHost +": " +mPort +". Error: ", e);
}
}
Snippet from the ConnectionListener:
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
System.out.println("success");
}else{
System.out.println("error");
}
}
EDIT:
If you want check the availability of the server withing the client App, you can use certain tools that Java7 can give us, for example, using this code:
private static boolean available(int port) {
try (Socket ignored = new Socket("localhost", port)) {
return false;
} catch (IOException ignored) {
return true;
}
}
This does not have to be a specific function Netty. More info here:
Sockets: Discover port availability using Java
Enjoy.
To check it outside you client app:
To test the server status I use the Hercules software client.If you know that server will respond someting, using hercules you can send a dummy data y wait the server response.
How you can see, Hercules, allows too makes a ping to the server :)
Hope it helps.