I am trying to deploy my Jersey project from eclipse on openshift and I am getting this error in the tail files Caused by: java.net.NoRouteToHostException: No route to host
before when I had like this:
String host = "jdbc:mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/bustrackerserver"
I got this error:
'java.lang.NumberFormatException: For input string: “OPENSHIFT_MYSQL_DB_PORT”'
I have pinged this ip address 127.10.230.440 and I am getting response
I checked whether some of the port 8080, 3306 are being used from my local mashine but they are just being used from eclipse.
Apple class.
package org.busTracker.serverSide;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "myresource" path)
*/
#Path("myresource")
public class Apple {
//String host = " jdbc:mysql://${env.OPENSHIFT_MYSQL_DB_HOST}:${env.OPENSHIFT_MYSQL_DB_PORT}/serverside";
//String host = "jdbc:mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/bustrackerserver";
String host = "jdbc:mysql://127.10.230.440:3306/bustrackerserver";
String user = "adminNMccsBr";
String password = "K3SV5rbxh8qP";
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* #return String that will be returned as a text/plain response.
*/
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database…");
conn = DriverManager.getConnection(host,user,password);
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// ignore
}
}
}
return "Hello, from apple class 14.05.15 13:30!";
}
}
Your MySQL is not listening on TCP/IP and hence your attempt to connect is failing. You sort of answered your question when you said:
I checked whether some of the port 8080, 3306 are being used from my local mashine but they are just being used from eclipse.
In other words, MySQL is not listening on localhost. To confirm this another way, try connecting to MySQL from the command prompt:
mysql -u adminNMccsBr -h 127.10.230.440 -p YOUR_DB_NAME
I expect this to fail. The solution to your problem is to configure MySQL to listen on localhost. In the /etc/my.cnf config file, under the [mysqld] line, add the following:
bind-address = 127.10.230.440
This is not a Java problem, it's a MySQL problem.
Related
I'm trying to establish a connection from Java to Oracle DB. (My DB is in another machine)
The form of URL as i know is like : String url = "jdbc:oracle:thin:#hostname:portnumber:sid";
And here is my Java code to establish a connection:
package net.metric.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text");
PrintWriter out = response.getWriter();
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return;
}
try{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//CONNECT TO DB
String url = "jdbc:oracle:thin:#252.112.60.47:1521:XE";
System.out.println(url);
Connection conn = DriverManager.getConnection(url,"EXT02501231","Tellcom30");
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
System.out.println("OK");
/* ResultSet rset =
stmt.executeQuery("select * from SBO_AUDIT_NEW.AUDIT_EVENT");
while (rset.next()) {
System.out.println (rset.getString(1));
}
stmt.close();
System.out.println ("Ok.");*/
}catch(Exception e){
System.out.println(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
I'm getting this error :
-------- Oracle JDBC Connection Testing ------
Io exception: The Network Adapter could not establish the connection
What am I doing wrong? Any answer would be appreciated..
Thanks
There are three ways to write to a jdbc url.
If you are connecting with service name you should put / before service name
jdbc:oracle:thin:#hostname:port/service_name --- In your case this is how you need the url
if you are connecting with sid you should put : before sid
jdbc:oracle:thin:#hostname:port:sid
or use the description in your tns file after #
jdbc:oracle:thin:#(DESCRIPTION=....)
BUT non of them are the cause for your problem. This error is not an SQLException. It is a TCP/IP connection exception. That means you somehow can not reach the machine.
Are you able to connect to the database with another client ? I see you are using TOAD. Are you able to connect with toad ? You need to make sure you can reach the server.
Try pinging to the machine on command line
ping 85.29.60.47
if you get response back then try telnet on the port
telnet 85.29.60.47 1521 -- You must have a telnet client installed to do that.
You will probably see either ping or telnet fails. So it is probably a firewall issue. What you need to do is to contact network administrators about the problem then.
This question already has an answer here:
MySQL Connect via proxy in Java
(1 answer)
Closed 2 years ago.
In Java, I would like to make a connection to a MySQL server which is on the web from a client computer that is behind a http proxy. I have read few solutions some say http tunnelling might work and some suggest a very old link from oracle which is not available anymore. So the question is:
How can we connect to a MySQL server from a computer which is behind a http proxy?
You can try the following code and see if it works. It worked for me over TCP
package indika.jdbc.connectivity;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class ConnectOverProxy {
public static void main(String[] args) {
new ConnectOverProxy();
}
public ConnectOverProxy() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
Properties info = new Properties();
//info.put("proxy_type", "4"); // SSL Tunneling
info.put("proxy_host", "[proxy host]");
info.put("proxy_port", "[proxy port]");
info.put("proxy_user", "[proxy user]");
info.put("proxy_password", "[proxy password]");
info.put("user", "[db user]");
info.put("password", "[db pass word]");
conn = DriverManager.getConnection("jdbc:mysql://[db host]/",info);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select NOW()");
rs.next();
System.out.println("Data- " + rs.getString(1));
rs.close();
stmt.close();
conn.close();
} catch (SQLException er) {
er.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Also look at "http://www.idssoftware.com/jdbchttps.html", However I have not used this personally.
I have a Java Webservice code . Currently I am running it on a localhost. What changes should be made when I run this on another server(with static IP).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
public class RetailerWS {
public String customerData(){
String customerInfo = "";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/retailer","root","chathura");
//Find customer information where the customer ID is maximum
PreparedStatement statement = con.prepareStatement("SELECT * FROM customers WHERE C_ID = (SELECT MAX(C_ID) FROM customers)");
ResultSet result = statement.executeQuery();
while(result.next()){
customerInfo = customerInfo + result.getString("name") + "&" + result.getString("C_ID") + "&"+result.getString("address") + "&"+result.getString("email");
//Here "&"s are added to the return string. This is help to split the string in Android application
}
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return customerInfo;
}
}
You need not to make any change if database is also hosted on the same server. If DB is on other server then change this line :
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/retailer","root","chathura");
to have the ip/address or hostname of your DB server.
Your web service clients need to use the address of you new server where you are hosting the web service, to call its methods.
I am using ssh factory to automate the logins. I have to automate logins till 4 gateways and send commands and get output's of it. I have successfully automated till 3 gateways. Now i have to fire command "telnet remote_ip" to get into the 4th gateway. Where i am using telnet sessions for this 4th gateway alone since i need to fire "telnet ip", since it is using telnet protocol over here. But for the previous 3 gateway's i've used ssh sessions. But it is not firing this "telnet ip" command. Can some1 help me regarding this?.
Below is the code, where i am trying to automate it.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import com.jscape.inet.ssh.Ssh;
import com.jscape.inet.ssh.SshAdapter;
import com.jscape.inet.ssh.SshConnectedEvent;
import com.jscape.inet.ssh.SshDataReceivedEvent;
import com.jscape.inet.ssh.SshDisconnectedEvent;
import com.jscape.inet.ssh.SshException;
import com.jscape.inet.ssh.SshScript;
import com.jscape.inet.ssh.SshSession;
import com.jscape.inet.ssh.SshTask;
import com.jscape.inet.ssh.connection.channels.SessionClient;
import com.jscape.inet.ssh.connection.channels.SessionRequests;
import com.jscape.inet.ssh.util.SshParameters;
import com.jscape.inet.telnet.Telnet;
import com.jscape.inet.telnet.TelnetException;
import com.jscape.inet.telnet.TelnetListener;
import com.jscape.inet.telnet.TelnetScript;
import com.jscape.inet.telnet.TelnetSession;
import com.jscape.inet.telnet.TelnetTask;
public class SshScriptTutorial extends SshAdapter {
public SshScriptTutorial() {}
public void executeSshScript(String hostname, String username, String password)
throws SshException, IOException, InterruptedException, TelnetException
{
// assumes that SSH shell prompt is ">" .. this MUST match exactly
String shellPrompt = ">";
String shellPrompt1 = ":";
// initialize and create new Ssh instance
SshParameters sshParams = new SshParameters(hostname,username,password);
Ssh ssh = new Ssh(sshParams);
// register this class to receive Ssh events
ssh.addSshListener(this);
// create new script object and bind to the given ssh object
SshScript script = new SshScript(ssh);
// add tasks to script object
script.addTask(new SshTask(shellPrompt, "show host", shellPrompt));
script.addTask(new SshTask(shellPrompt, "ssh ssgpun", shellPrompt1)); // 2nd g/w
script.addTask(new SshTask(shellPrompt1, "password", shellPrompt));
script.addTask(new SshTask(shellPrompt, "net ip", shellPrompt1)); // 3rd gateway
script.addTask(new SshTask(shellPrompt1, "username", shellPrompt1));
script.addTask(new SshTask(shellPrompt1, "password", shellPrompt));
// till this it is working
// connect to SSH server and execute script
ssh.connect();
// wait until last task is complete
while(!script.isComplete()) {
try {
Thread.sleep(500);
} catch(Exception e) {
System.err.println(e.getMessage());
}
}
// disconnect from server
// ssh.disconnect();
//**
Here i am trying to get into the last remote server using command "telnet ip" using telnet session since it is involving telnet protocol. But it is not firing this command itself. So, can anybody help me regarding this. How to do?... I have even tried using ssh sessions for this "telnet ip" and for username and pass. If i use ssh session for this 4th gateway, i am able to automate only "telnet ip" and it is asking for login name, and login name is not automated. So, i have tried both ssh sessions and telnet sessions. I dont know what is the prob or how to solve it.
Kindly help...
//**
// create new Telnet instance
Telnet telnet = new Telnet("10.228.128.33");
// create new TelnetScript instance and bind to Telnet instance
TelnetScript script_t = new TelnetScript(telnet);
// create a task that waits for login prompt and submits username
TelnetTask username_t = new TelnetTask(shellPrompt1,"switchind", shellPrompt1);
// create task that waits for password prompt and submits password
TelnetTask password_t = new TelnetTask(shellPrompt1, "Indore123", shellPrompt);
// add tasks to script
script_t.addTask(username_t);
script_t.addTask(password_t);
// connect to telnet server … script is executed automatically
telnet.connect();
}
public void connected(SshConnectedEvent event) {
System.out.println("Connected to host: " + event.getHost());
}
public void disconnected(SshDisconnectedEvent event) {
System.out.println("Disconnected from host: " + event.getHost());
}
public void dataReceived(SshDataReceivedEvent event) {
System.out.print(event.getData());
}
public static void main(String[] args)
{
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String hostname = "host_ip";
String username = "username";
System.out.print("Enter password: ");
String password = reader.readLine();
SshScriptTutorial tutorial = new SshScriptTutorial();
tutorial.executeSshScript(hostname, username, password);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Any idea why do I get RemoteException while trying to invoke methods on Unix machine from Windows?
I am inside the network and don't think this is because of firewall problem as I can do "telnet" from Windows to Unix box after starting the RMI server at the unix box. I also could not understand why is it going to local loopback IP?
Stack Trace:
RemoteException occured, details java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is:
java.net.ConnectException: Connection refused: connect
java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is:
java.net.ConnectException: Connection refused: connect
Many thanks in advance.
You probably don't have your hostname configured properly on your Linux box. I bet if you ping $(hostname) from your Linux box, it will ping 127.0.0.1. Usually this is because of an entry in your /etc/hosts file.
There's a couple of ways to solve the problem. The hard way would be to get your Linux box to resolve its own hostname to its IP address properly. You can edit your /etc/hosts file, setup your DNS server, whatever you've got to do. The challenge is that while this may make things more technically correct, you run the risk of breaking things that relied on the old behavior.
The path of least change would be to set the system property java.rmi.server.hostname to the hostname or IP address of your Linux box. (i.e. java -Djava.rmi.server.hostname=$(hostname) ...).
Why?
The Java RMI registration server is actually a network wide registration server. Objects on other machines can bind themselves to this registry.
When a remote object is registered, the registration includes the network address as part of the registration. By default, the address it uses is 'the IP address of the local host, in "dotted-quad" format.' In your setup, this address is 127.0.0.1.
When your Windows box contacts the registration service for the address of the remote object, it gets back 127.0.0.1. It then tries to contact the remote object at that address. That's why it's going to the loopback address.
I suggest a solution based on customized RMISocketFactory.
Like explained on Sun Site, you can provide your own SocketFactory :
http://docs.oracle.com/javase/7/docs/technotes/guides/rmi/socketfactory/
My solution use this mecanism for intercept client socket creation, and replace the host received (127.0.0.1) by the good IP, well known by the client.
Th rest of the communication mechanism is still based on java rmi standards.
With this implementation, the exporter does not have to know it's own IP, which is sometimes no easy (multiple network interfaces ...)
Here are the tree classes, the Factory, the Server and the Client. The Hello class and interface are also uploaded to be exhaustive.
Hope it should be utile
SocketFactory:
import java.io.IOException;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.server.RMISocketFactory;
/**
* Socket Factory for RMI calls.
*
* This classe, instanciated from server when RMI objects are exported, is send
* to the client who use it (transparently) for create sockets which call remote objects.
*
* This implementation give the ability to modify dynamically the target host cible.
*
* The host will not be aware of it's own IP.
*/
public class MySocketFactory extends RMISocketFactory implements Serializable {
/**Target host for RMI calls, setted by caller. */
private static String server = "localhost";
/**
* Create a client socket, replacing required host by the host setted when the service is called,
* via {#link #setServer(String)}.
* The host received is usually 127.0.0.1, depending on property java.rmi.server.hostname on the exporter.
*/
#Override
public Socket createSocket(String host, int port) throws IOException {
System.out.println("change host from " + host + " to " + server);
return getFactory().createSocket(server, port);
}
/**
* Create a server socket.
*/
#Override
public ServerSocket createServerSocket(int port) throws IOException {
return getFactory().createServerSocket(port);
}
/**
* Use default RMI factory.
*/
private RMISocketFactory getFactory() {
return RMISocketFactory.getDefaultSocketFactory();
}
/**
* Save the target host. This method must be called before use of a service (before Naming.lookup).
*/
public static void setServer(String host) {
server = host;
}
}
Exporter :
import java.io.IOException;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RMISocketFactory;
import java.rmi.server.UnicastRemoteObject;
/**
* RmiExport
*/
public class MyRmiExporter {
/**
* java -Djava.security.policy=java.policy MyRmiExporter
*/
public static void main(String[] args) throws RemoteException, IOException {
System.setSecurityManager(new RMISecurityManager());
Hello export = new HelloImpl();
RMISocketFactory sf = new MySocketFactory();
UnicastRemoteObject.unexportObject(export, true);
Remote stub = UnicastRemoteObject.exportObject(export, 0, sf, sf);
String url = "rmi://0.0.0.0:" + Registry.REGISTRY_PORT + "/Hello";
LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
Naming.rebind(url, stub);
System.out.println("Exported " + url);
}
}
Client :
import java.io.IOException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.registry.Registry;
public class MyClient {
/**
* java MyClient localhost
*/
public static void main(String[] args) throws IOException, NotBoundException, InterruptedException {
String host = args[0];
MySocketFactory.setServer(host);
String url = "rmi://" + host + ":" + Registry.REGISTRY_PORT + "/Hello";;
System.out.println("look up " + url);
Hello proxy = (Hello) Naming.lookup(url);
System.out.println("OK, remote getted !");
System.out.println(proxy.hello("bonjour"));
}
}
Bean :
import java.io.Serializable;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Hello extends Remote, Serializable {
String hello(String mess) throws RemoteException;
}
Impl :
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class HelloImpl extends UnicastRemoteObject implements Hello {
public HelloImpl() throws RemoteException {
}
#Override
public String hello(String mess) throws RemoteException {
return "hello : " + mess;
}
}
last and least, java.policy :
grant {
permission java.security.AllPermission;
};