Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null - eclipse

I have written following code in my application:
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
public static final String JDBC_URL = "jdbc:derby:c:/coopcashier/db/COOP;create=true";
try {
Class.forName(DRIVER);
Connection conn = DriverManager.getConnection(JDBC_URL);
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery("select * from USERS");
while(resultset.next()) {
if(resultset.getString(4).toString().equals(txtUsername) && resultset.getString(5).toString().equals(txtPassword)) {
homePage home = new homePage();
setVisible(false);
home.setVisible(true);
}
else {
JOptionPane.showMessageDialog(null,"Invalid Username or Password.","Invalid Credentials",JOptionPane.ERROR_MESSAGE);
}
}
if(conn != null) conn.close();
if(statement != null) statement.close();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e2) {
e2.printStackTrace();
}
When I am running this in Eclipse, everything goes well. But when I made the jar file of my project with same code and try to run, it always throw following exception:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null
I could not find solution. Please share if anybody resolved this problem.
TIA

Related

java.sql.SQLSyntaxErrorException: Table/View 'USERS' does not exist

I have written as small code for standalone application where user can enter username and password to login. Application is designed to fetch these login details from USERS table COOP database.
Everything working properly when I run this in Eclipse. But when I run jar file of this project I got this message:
java.sql.SQLSyntaxErrorException: Table/View 'USERS' does not exist.
Please help to resolve this problem.
I am using apache derby.
below is the code:
String txtUsername = txtUserName.getText();
char[] password = passPassword.getPassword();
String txtPassword = new String(password);
try {
Class.forName(DRIVER);
Connection conn = DriverManager.getConnection(JDBC_URL);
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery("select * from USERS");
while(resultset.next()) {
if(resultset.getString(4).toString().equals(txtUsername) && resultset.getString(5).toString().equals(txtPassword)) {
homePage home = new homePage();
setVisible(false);
home.setVisible(true);
}
else {
JOptionPane.showMessageDialog(null,"Invalid Username or Password.","Invalid Credentials",JOptionPane.ERROR_MESSAGE);
}
}
//if(statement != null) statement.close();
if(conn != null) conn.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}

CachedRowSet always returns empty

public CachedRowSet execute(String asql) throws ServiceUnavailableException {
try (Connection connection = getDatabaseConnection();
Statement statement = connection.createStatement();) {
try (ResultSet resultSet = statement.executeQuery(asql);
CachedRowSet rowset = CachedRowSetFactory.getCachedRowSet()) {
rowset.populate(resultSet);
return rowset;
}
} catch (SQLException se) {
throw new ServiceUnavailableException("Database broken " + se);
} catch (Exception ne) {
throw new ServiceUnavailableException("JNDI Lookup broken ");
}
return null;
}
Hi everyone. I have a sample code as above. The problem is that returned rowset is always empty, even though there are lots of data in database.
Any suggestions? Thank you.

Junit testing for database conection

Is there a way to test below code.Here I am connecting to database with JNDI.I am new to mockito and not getting a way to test the same.
#SuppressWarnings("unused")
public Connection getJNDIConnection() {
Connection result = null;
try {
InitialContext initialContext = new InitialContext();
if (initialContext == null) {
LOGGER.info("JNDI problem. Cannot get InitialContext.");
}
DataSource datasource = (DataSource) initialContext.lookup(jndiName);
if (datasource != null) {
result = datasource.getConnection();
} else {
LOGGER.info("Failed to lookup datasource.");
}
} catch (NamingException ex) {
LOGGER.error("Cannot get connection: " + ex);
} catch (SQLException ex) {
LOGGER.error("Cannot get connection: " + ex);
}
return result;
}
Of course, you can to do it, but I think you should read the documentation yourself. The main points here is:
InitialContext initialContext = mock(InitialContext.class);
DataSource dataSource = mock(DataSource.class);
Connection expected = mock(Connection.class);
whenNew(InitialContext.class).withNoArguments().thenReturn(initialContext);
when(initialContext.lookup(jndiName)).thenReturn(dataSource);
when(initialContext.getConnection()).thenReturn(connection);
Connection result = intatnceOfCalss.getJNDIConnection();
assertSame("Should be equals", expected, result);
Also you should use PowerMock to mock constructors and static methods. To have deal with Logger, just add this code:
#BeforeClass
public static void setUpClass() {
mockStatic(LoggerFactory.class);
Logger logger = mock(Logger.class);
when(LoggerFactory.getLogger(ApplySqlFileIfExistsChange.class)).thenReturn(logger);
}
Don't forget about annotations:
#RunWith(PowerMockRunner.class)
#PrepareForTest({LoggerFactory.class})
Try to read this doc http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html

Servlet running on Tomcat in Eclipse but not displaying on Ubuntu Server Tomcat

I have a servlet as follows that is running perfectly on my Eclipse tomcat. When I upload it to the webapps folder and restart my tomcat on my Ubuntu server, the URL for it(/ServerAPP/Login) won't load, though the tomcat root page does fine. If anyone has any idea why this is happening, I would greatly appreciate it. I'm fairly new to Ubuntu and the inner workings of Tomcat so I could have missed anything.
I can give more information on request, I'm just not sure how much is needed, or if there's something simple and stupid I'm not thinking about.
package Actions;
import java.io.*;
import java.sql.*;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.sql.DataSource;
#WebServlet(urlPatterns={"/Login"})
public class Login extends HttpServlet implements DataSource {
private String User = null;
Connection connection = null;
private String password = null;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(request.getParameter("User") != null){
this.setUser((String) request.getParameter("User").toString());
}
if(request.getParameter("password") != null){
this.setPassword((String) request.getParameter("password").toString());
}
try {
System.out.println("Loading driver...");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot find the driver in the classpath!", e);
}
Login ds = new Login();
try {
connection = ds.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter out = response.getWriter();
if(connection != null){
//out.println(User + " " + password);
//Check if user exists in database
if(User!= null){
Statement stmt;
ResultSet rs;
try {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM tblUsers WHERE Username = '" + User + "';");
if(!rs.next()){
out.println("Username: " + User + " was not found in Users table.");
}
else{
//User was found now check if password is correct
if(rs.getString(3).equals(password)){
out.println("User: " + User + " login successful!");
}
else if(rs.getString(3).equals(password) == false){
//password was incorrect
out.println("Password incorrect!");
}
/*
while(rs.next()){
out.println("User ID: " + rs.getInt(1) + " Username: " + rs.getString(2));
}
*/
}
rs.close();
stmt.close();
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
Statement stmt;
ResultSet rs;
try {
stmt = connection.createStatement();
rs = stmt.executeQuery("Select * from tblUsers;");
while(rs.next()){
out.println("User ID: " + rs.getInt(1) + " Username: " + rs.getString(2));
}
rs.close();
stmt.close();
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
}
#Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}
#Override
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub
}
#Override
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub
}
#Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
#Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}
#Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
#Override
public Connection getConnection() throws SQLException {
if (connection != null) {
System.out.println("Cant craete a Connection");
} else {
connection = DriverManager.getConnection(
"<redacted>", "AWSCards", "Cards9876");
}
return connection;
}
#Override
public Connection getConnection(String username, String password)
throws SQLException {
// TODO Auto-generated method stub
if (connection != null) {
System.out.println("Cant craete a Connection");
} else {
connection = DriverManager.getConnection(
"<redacted>", username, password);
}
return connection;
}
public String getUser() {
return User;
}
public void setUser(String user) {
User = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
So I ended up figuring it out, and I thought it might help others to know.
Reason:
Apparently, my tomcat on ubuntu was only java 6, while my eclipse was targeting java 7.
Fix:
I went to the project properties and changed the target(which made eclipse mad), but then recompiled it and put it on the tomcat on ubuntu, and it works fine.
Thanks to the people who tried to help me.

A network related error or instance-specific error occured while establishing a connection to sql server

This is the error which arises when I tried to debug an application under Visual C# 2010
I write that code to retrieve some rows from a database table, I already attached the two well known databases Pubs and Northwind to the db explorer, but the error remains
class Author
{
SqlConnection _pubConnection;
string _connString;
public Author()
{
_connString = "Data Source=./INSTANCE2;Initial Catalog=pubs;Integrated Security=True";
_pubConnection = new SqlConnection();
_pubConnection.ConnectionString = _connString;
}
public int CountAuthors()
{
try
{
SqlCommand pubCommand = new SqlCommand();
pubCommand.Connection = _pubConnection;
pubCommand.CommandText = "Select Count(au_id) from authors";
_pubConnection.Open();
return (int)pubCommand.ExecuteScalar();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
if (_pubConnection != null)
{
_pubConnection.Close();
}
}
}
}
static void Main(string[] args)
{
try
{
Author author = new Author();
Console.WriteLine(author.CountAuthors());
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
the Connection string isn't ok , i correct it and it works fine