There are other similar questions to this, but I don't feel like it answers mine. From a Java servlet I need to be able to ssh to any server on my company's network and dynamically handle this unknown key exception and then issue a command to get and display the current status of the server.
I saw one suggestion to use JSch session.setFingerprint, but it must have changed or something because far as I can tell, it doesn't exist. I'm using Netbeans.
Here's my code:
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String url = "validurl";
String user = "validuser";
String password = "validpassword";
printer.println ("HelloWorld!");
JSch ssh = new JSch();
ChannelShell ch = null;
Session session = null;
try {
session = ssh.getSession(user, "serverIP", 22);
session.setPassword(password);
session.connect();
ch = (ChannelShell)session.openChannel("shell");
ch.connect();
}
catch (JSchException e) {
System.out.println ("Exception: " + e);
}
catch (Exception e) {
System.out.println ("Exception: " + e);
}
Thanks!
Devin
Related
I've a servlet that checks username and password from database.
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mvs_user", "root", "pass");
if (req.getParameter("usrnm") != null && req.getParameter("pwd") != null) {
String username = req.getParameter("usrnm");
String userpass = req.getParameter("pwd");
String strQuery = "select * from user where username='" + username + "' and password='" + userpass + "'";
System.out.println(strQuery);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(strQuery);
if (rs.next()) {
req.getSession(true).setAttribute("username", rs.getString(2));
res.sendRedirect("adminHome.jsp");
} else {
res.sendRedirect("index.jsp");
}
} else {
res.sendRedirect("login.jsp");
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is the browser only displays a blank page and yet I expect it to display "Hello World" in the redirected page. Where could the problem be? Please help me troubleshoot.
You need to properly handle exceptions. You should not only print them but really throw them.
Replace
} catch (Exception e) {
e.printStackTrace(); // Or System.out.println(e);
}
by
} catch (Exception e) {
throw new ServletException("Login failed", e);
}
With this change, you will now get a normal error page with a complete stacktrace about the cause of the problem. You can of course also just dig in the server logs to find the stacktrace which you just printed instead of rethrowed.
There are several possible causes of your problem. Maybe a ClassNotFoundException or a SQLException. All which should be self-explaining and googlable.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
The infamous java.sql.SQLException: No suitable driver found
Unrelated to the concrete problem, your JDBC code is prone to resource leaking and SQL injection attacks. Do a research on that as well and fix accordingly.
We were working on deadlock issue and went to a solution where we are catching the deadlock exception and resubmitting for 6 times. users are happy that they didnt get any errors but a new error thrown after 2 hours moved to production with the below error "Usp_updateXXXX is throwing has too many arguements" . This issue is happening whenever the app encounters deaadlock exception.
Please find the code snippet below
{
//msg = string.Empty;
SqlConnection _con = new SqlConnection(Conn);
SqlCommand _cmd = new SqlCommand();
SqlDataAdapter _adp = new SqlDataAdapter(_cmd);
_cmd.Connection = _con;
bool isDeadlock = false;
int reTry = 0;
//Check for Deadlock and retry for 6 times to send the same request
do
{
msg = string.Empty;
try
{
_con.Open();
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.CommandText = "usp_UpdateXXXX";
//Assign the command parametrs
_cmd.ExecuteNonQuery();
isDeadlock = false;
}
catch (Exception ex)
{
if ((ex.Message.Contains("was deadlocked on lock resources with another process and has been chosen as the deadlock victim")) || (ex.Message.Contains("deadlock")) || (ex.Message.Contains("Transaction (Process ID")))
{
isDeadlock = true;
Thread.Sleep(5000);
reTry++;
}
else
{
msg = ex.Message;
isDeadlock = false;
}
}
finally
{
con.Close();
}
} while (reTry < 6 && isDeadlock == true);
Can any one help me where is the code bug which causing to throw the exception.
Regards
Prashant
The issue happened because of the looping used. Actually when the exception happens it is again going to call the loop without clearing the existing parameters hence its adding the new parameters .
To resolve this issue I cleared the parameters once its in the exception section.
try{
//statements here
}
catch (Exception ex)
{
if ((ex.Message.Contains("was deadlocked on lock resources with another process and has been chosen as the deadlock victim")) || (ex.Message.Contains("deadlock")) || (ex.Message.Contains("Transaction (Process ID")))
{
//used below statement
command.Parameters.Clear() ;
isDeadlock = true;
Thread.Sleep(5000);
reTry++;
}
else
{
msg = ex.Message;
isDeadlock = false;
}
}
This resolved my prob.
Regards
Prashant
I am working on a web application using jsp and servlet using oracle.jdbc.OracleDriver.This code,working fine on my PC,but when trying to deploy build of application on other server,i am getting Exception like this.
java.sql.SQLException: Missing defines
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:158)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:305)
at oracle.jdbc.driver.OracleStatement.prepareAccessors(OracleStatement.java:793)
at oracle.jdbc.driver.T4CResultSetAccessor.getCursor(T4CResultSetAccessor.java:235)
at oracle.jdbc.driver.ResultSetAccessor.getObject(ResultSetAccessor.java:95)
at oracle.jdbc.driver.OracleCallableStatement.getObject(OracleCallableStatement.java:1947)
at org.apache.tomcat.dbcp.dbcp.DelegatingCallableStatement.getObject(DelegatingCallableStatement.java:143)
at cwep.Login.processRequest(Login.java:127)
at cwep.Login.doPost(Login.java:198)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:852)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:584)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1508)
at java.lang.Thread.run(Unknown Source)
After debugging my application,i found that when I am calling database(Oracle 10g) procedure on server side and getting cursor using callableStatement.registerOutParameter(1,OracleTypes.CURSOR), I am getting above Exception at
callableStatement.execute(); statement.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
static String CNPOOL = "cnpool";//Getting CNPOOL correctly for database connection
CallableStatement cs = null;
static DataSource dataSource;//Declared as global
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
CallableStatement cs = null;
String str = conectionPool;
System.out.println(str);
try {
InitialContext initContext = new InitialContext();
Context context = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) context.lookup(str);
System.out.println(" CxN Pool " + str);
String username = request.getParameter("username");
String password = request.getParameter("password");
ecode = Integer.parseInt(username);
System.out.println(" eCode " + ecode);
try {
con = ConnectionBean.getConnection(dataSource);
System.out.println(" CxN " + con.toString());
} catch (Exception e) {
System.out.println(" Opening the Cxn 1st Time" + e);
}
if(con!=null)
{
System.out.println(" Before Calling proc_user_login " + ecode);
cs = con.prepareCall("{call proc_user_login(?,?,?,?,?)}");
cs.setInt(1, empcode);
cs.setString(2, password);
cs.registerOutParameter(3, Types.NUMERIC);
cs.registerOutParameter(4, Types.NUMERIC);
cs.registerOutParameter(5, Types.VARCHAR);
try {
cs.execute();
} catch (Exception e) {
System.out.println("--------------------After executing first proc----------------------- ");
}
int message = cs.getInt(3);
if (message == 0) {
cs = con.prepareCall("{call proc_get_XXXlist(?,?)}");
cs.setInt(1, empcode);
cs.registerOutParameter(2, OracleTypes.CURSOR);
try {
System.out.println("Before executing XXXList proc ");
cs.execute(); //GETTING EXCEPTION AT THIS STATEMENT
System.out.println("After executing XXXList");
} catch (Exception e) {
System.out.println("exception in After executing secod proc ");
}
ResultSet rset = (ResultSet) cs.getObject(2);
Vector v1 = new Vector();
Vector v2 = new Vector();
Vector v3 = new Vector();
while (rset.next()) {
v1.addElement(rset.getString(1));
v2.addElement(rset.getString(2));
v3.addElement(rset.getString(3));
}
//rset.last();
String[] str1 = new String[v1.size()];
String[] str2 = new String[v2.size()];
String[] str3 = new String[v3.size()];
v1.copyInto(str1);
v2.copyInto(str2);
v3.copyInto(str3);
request.setAttribute("ecode", Integer.toString(ecode));
request.setAttribute("clientid", str1);
request.setAttribute("constring", str2);
request.setAttribute("URL", str3);
RequestDispatcher rd = request.getRequestDispatcher("XXX.jsp");
rd.forward(request, response);
//response.sendRedirect("XXX.jsp");
} else {
response.sendRedirect("index.jsp?val=" + message);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("EEE---" + e);
Utility.log("FinalExceptionToServlet.namelookup:", e.toString(), "SERVER", "E");
}
}
In this code,First database login_usr procedure execute properly,but when trying to execute 2nd procedure,which returns a cursor as outparameter,i'm getting above exception.If same code working fine on my PC,then why it throws exception when trying to execute callablestatement after Serverside deployment.Here I'm using Ojdbc14.jar and classes12.jar.Is there is any .jar missmatch..???
Thanks in advance.
As you have mentioned that the code was running earlier, Here the culprit could be OracleTypes. As its abstract class you need correct and concrete implementation of it which is your Driver.
Verify the version of the JDBC driver and the type of JDBC driver (Thin or OCI) you
Download new jar from oracle site or from here.
Also, try using oracle.jdbc.OracleTypes before looking for drivers.
e.g. cn.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);
I have a little problem.
In this code, always there is catch{} section firing. Even if any exception is thrown. I checked in debugger and no exception is THROWN but somehow code from catch{} is firing and it transfers me to google.com.
If I comment the code from catch{}, Page is running fine.
Someone know why is that? It makes me mad.
Thanks
protected void Button5_Click(object sender, EventArgs e)
{
if (Page.IsValid == true)
{
try
{
conn = new MySqlConnection("Server=localhost;Port=3306;Database=ewidencja;Uid=webuser;Pwd=web1;");
conn.Open();
MySqlDataAdapter mda = new MySqlDataAdapter();
mda.SelectCommand = new MySqlCommand("select id from pacjenci where pesel='" + Session["pesel"].ToString() + "';", conn);
int id_pacjenta = (int)mda.SelectCommand.ExecuteScalar();
int id_lekarza=Int32.Parse(DropDownList1.SelectedValue);
mda.InsertCommand = new MySqlCommand("insert into planowane_wizyty (id_pacjenta, id_lekarza, data_wizyty) values(" + id_pacjenta + ", " + id_lekarza + ", '" + Calendar1.SelectedDate.ToString().Substring(0,10)+" "+ ListBox1.SelectedItem.Value + "');", conn);
if (mda.InsertCommand.ExecuteNonQuery() == 1)
Response.Redirect("wizyty.aspx");
else
Response.Redirect("info.aspx");
}
catch (Exception ex)
{
Response.Redirect("http://www.google.com");
}
}
}
Response.Redirect can throw a ThreadAbortException. This then hits the outer exception handler, triggering the second Response.Redirect.
See Why Response.Redirect causes System.Threading.ThreadAbortException?
More importantly, this is one reason that data access code should not be mixed so tightly with UI behavior. Debugging such code is difficult, unit testing is near impossible, and reusability is low.
It also looks like your query is being constructed via string concatenation, which is vulnerable to SQL injection. Parameterize the query instead.
The overload of Response.Redirect you are using will always try and stop the current thread. This causes the exception you are seeing. System.Threading.ThreadAbortException
There is an overload available: Response.Redirect(string url, bool endResponse) that allows you to control whether to end the current thread using the endResponse parameter.
All that being said, you can catch this specific error and ignore it. The suggestion below is just one of a few solutions you can implement. It all depends on what you are trying to do.
protected void Button5_Click(object sender, EventArgs e)
{
if (Page.IsValid == true)
{
try
{
conn = new MySqlConnection("Server=localhost;Port=3306;Database=ewidencja;Uid=webuser;Pwd=web1;");
conn.Open();
MySqlDataAdapter mda = new MySqlDataAdapter();
mda.SelectCommand = new MySqlCommand("select id from pacjenci where pesel='" + Session["pesel"].ToString() + "';", conn);
int id_pacjenta = (int)mda.SelectCommand.ExecuteScalar();
int id_lekarza=Int32.Parse(DropDownList1.SelectedValue);
mda.InsertCommand = new MySqlCommand("insert into planowane_wizyty (id_pacjenta, id_lekarza, data_wizyty) values(" + id_pacjenta + ", " + id_lekarza + ", '" + Calendar1.SelectedDate.ToString().Substring(0,10)+" "+ ListBox1.SelectedItem.Value + "');", conn);
if (mda.InsertCommand.ExecuteNonQuery() == 1)
Response.Redirect("wizyty.aspx");
else
Response.Redirect("info.aspx");
}
catch (System.Threading.ThreadAbortException)
{
//do nothing. This is an expected error stemming from Response.Redirect
}
catch (Exception ex)
{
Response.Redirect("http://www.google.com");
}
}
}
I've a servlet that checks username and password from database.
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mvs_user", "root", "pass");
if (req.getParameter("usrnm") != null && req.getParameter("pwd") != null) {
String username = req.getParameter("usrnm");
String userpass = req.getParameter("pwd");
String strQuery = "select * from user where username='" + username + "' and password='" + userpass + "'";
System.out.println(strQuery);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(strQuery);
if (rs.next()) {
req.getSession(true).setAttribute("username", rs.getString(2));
res.sendRedirect("adminHome.jsp");
} else {
res.sendRedirect("index.jsp");
}
} else {
res.sendRedirect("login.jsp");
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is the browser only displays a blank page and yet I expect it to display "Hello World" in the redirected page. Where could the problem be? Please help me troubleshoot.
You need to properly handle exceptions. You should not only print them but really throw them.
Replace
} catch (Exception e) {
e.printStackTrace(); // Or System.out.println(e);
}
by
} catch (Exception e) {
throw new ServletException("Login failed", e);
}
With this change, you will now get a normal error page with a complete stacktrace about the cause of the problem. You can of course also just dig in the server logs to find the stacktrace which you just printed instead of rethrowed.
There are several possible causes of your problem. Maybe a ClassNotFoundException or a SQLException. All which should be self-explaining and googlable.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
The infamous java.sql.SQLException: No suitable driver found
Unrelated to the concrete problem, your JDBC code is prone to resource leaking and SQL injection attacks. Do a research on that as well and fix accordingly.