Java error: The url cannot be null ( netbeans and wampserver) - mysql

I'm creating a Java application (stock management) with NetBeans and WampServer, I create the stock_db_connection class and the Login class, and I want to test if it's work or not, when I click run file, the login window appear; I enter the username and password but when I click "Login", I get the following error:
The url cannot be null
The url cannot be null
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at stockmanagment.Stock_db_connection.exectionQuery(Stock_db_connection.java:58)
at stockmanagment.Stock_db_connection.querySelectAll(Stock_db_connection.java:97)
at database.Login.loginActionPerformed(Login.java:117)
at database.Login.access$200(Login.java:10)
at database.Login$3.actionPerformed(Login.java:79)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6527)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6292)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4883)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4705)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4705)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:719)
at java.awt.EventQueue$4.run(EventQueue.java:717)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
I don't know what is the problem, please can you help me...
This is the code of Login button.
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
rs = db.querySelectAll("utilisateur", "username='" + txt_username.getText()
+ "' and password='" + txt_password.getText() + " '");
try {
while (rs.next()) {
username1 = rs.getString("username");
password1 = rs.getString("password");
hak = rs.getString("type");
}
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
if (username1 == null && password1 == null) {
JOptionPane.showMessageDialog(this, "le nom utilisateur ou le mots de pass est incorrect");
} else {
if (hak.equals("directeur")) {
Produits h = new Produits();
h.setVisible(true);
this.dispose();
} else {
Chauffeurs k = new Chauffeurs();
k.setVisible(true);
this.dispose();
}
}
}

Related

WARN:oejw.WebAppContext:Thread-5113: Failed startup of context o.e.j.w.WebAppContext- java.lang.NullPointerException

Our project has two servers if one server is closed then it should connect to the another one. But I'm getting this error while doing so. It is not connecting either.
WARN:oejw.WebAppContext:Thread-5113: Failed startup of context o.e.j.w.WebAppContext#1b14e897{/,file:///cots/ENet/webserver/webapps/cgiAdapter/,UNAVAILABLE}+
java.lang.NullPointerException+
at org.eclipse.jetty.webapp.MetaInfConfiguration.scanJars(MetaInfConfiguration.java:143)+
at org.eclipse.jetty.webapp.MetaInfConfiguration.preConfigure(MetaInfConfiguration.java:102)+
at org.eclipse.jetty.webapp.WebAppContext.preConfigure(WebAppContext.java:506)+
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:544)+
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)+
at geh.appserver.webserver.WebServerManager.systemInfoChanged(WebServerManager.java:681)+
at geh.appserver.AppServerController.sendSystemInformation(AppServerController.java:12344)+
at geh.appserver.AppServerBrokerImpl.sendSystemInformation(AppServerBrokerImpl.java:966)+
at geh.agent.XaDynamicDataManager$48.run(cd ME:13666)
java.lang.IllegalStateException: STARTED
Here's the code:
public void systemInfoChanged(boolean inStandbyMode) {
logger.log(Logger.INFO, "systemInfoChanged - inStandbyMode = " + inStandbyMode);
for (Iterator i = connectorList.iterator(); i.hasNext();) {
WebServerConnector wsc = (WebServerConnector) i.next();
if (inStandbyMode) {
logger.log(Logger.DEBUG, "SHUTDOWN SISO CONTEXTS FOR ADDRESS [ " + wsc.getAddress() + " ] PORT [ "
+ wsc.getPort() + " ]");
if (sisoContexts != null)
{
for (int c = 0; c < sisoContexts.getHandlers().length; c++) {
try {
sisoContexts.getHandlers()[c].stop();
} catch (Exception e) {
logger.log(Logger.ERROR, "Error occurred while stopping handler");
e.printStackTrace();
}
allContexts.removeHandler(sisoContexts.getHandlers()[c]);
}
sisoContexts = new ContextHandlerCollection();
sisoContexts.setHandlers(new Handler[] {}); //empty handler collection
sisoUp = false;
}
} else {
logger.log(Logger.DEBUG, "STARTUP SISO CONTEXTS FOR ADDRESS [ " + wsc.getAddress() + " ] PORT [ "
+ wsc.getPort() + " ]");
WebAppContext cgiContext = new WebAppContext();
cgiContext.setDescriptor(root + fileSeparator + "webapps" + fileSeparator + "cgiAdapter" + "/WEB-INF/web.xml");
cgiContext.setResourceBase(root + fileSeparator + "webapps" + fileSeparator + "cgiAdapter");
cgiContext.setAttribute(
"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );
if (!sisoUp) {
try {
cgiContext.start(); // start handler before adding back
// to the server
allContexts.addHandler(cgiContext);
sisoContexts.addHandler(cgiContext);
sisoUp = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

How to format the response from the servlet, so the dojo does not return an exception

According to the dojo tutorial and several examples here, I am trying to send multiple multiple file help. The files to the servlet will arrive in the directory, but the dojo will return the exception
I use dojo 1.10 and javax.servlet.http.HttpServlet v3.0.1
PrintWriter out = response.getWriter();
try {
if (ServletFileUpload.isMultipartContent(request)) {
try {
#SuppressWarnings("unchecked")
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File("/tmp/eshop/" + File.separator + name));
}
}
out.print("[{uploadresult:'Upload is ok!'}]");
} catch (Exception ex) {
out.print("{uploadresult: 'File upload failed due to : '" + ex+"}");
}
} else {
out.print("{uploadresult:'Sorry this servlet only handles file upload request.'}");
}
out.close();
} catch (Exception e) {
logger.error(e);
}
Error thrown :
/dojo/v1.10/dojox/form/uploader/_HTML5.js:80 Error parsing server
result: SyntaxError: Unexpected token u in JSON at position 2
at JSON.parse ()
at Object.eval (/dojo/v1.10/dojox/form/uploader/_HTML5.js:76)
at XMLHttpRequest. (dojo.js: 15) (anonymous) # /dojo/v1.10/dojox/form/uploader/_HTML5.js:80
/dojo/v1.10/dojox/form/uploader/_HTML5.js:81 [{uploadresult: 'Upload
is ok!'}]
First of all , set the response to json format
add first the response.setContentType("application/json");
And you thing you've to format the json correctly by adding quotes to the key like :
response.setContentType("application/json");
PrintWriter out = response.getWriter();
try {
if (ServletFileUpload.isMultipartContent(request)) {
try {
#SuppressWarnings("unchecked")
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File("/tmp/eshop/" + File.separator + name));
}
}
out.print("[{'uploadresult':'Upload is ok!'}]");
} catch (Exception ex) {
out.print("{'uploadresult': 'File upload failed due to : '" + ex+"}");
}
} else {
out.print("{'uploadresult':'Sorry this servlet only handles file upload request.'}");
}
out.close();
} catch (Exception e) {
logger.error(e);
}

Displaying data in database without using json

Somehow I got arround with Class.forName("com.mysql.jdbc.Driver");
having class not found exception error but I dont know if it works. I
just added permissions, but now every time i run this app on my
emulator it keeps on catching to SQLException which I set to display
error2.
Why is it not showing my data from my database,,is there something wrong with my code?
public void connDB() {
TextView myTextView = (TextView) findViewById(R.id.text);
try {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
String result = "Database connection success";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Scraped");
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
result += rsmd.getColumnName(1) + ":" + rs.getString(1) + "\n";
result += rsmd.getColumnName(2) + ":" + rs.getString(2) + "\n";
result += rsmd.getColumnName(3) + ":" + rs.getString(3) + "\n";
result += rsmd.getColumnName(4) + ":" + rs.getString(4) + "\n";
result += rsmd.getColumnName(5) + ":" + rs.getString(5) + "\n";
}
myTextView.setText(result);
} catch (ClassNotFoundException e) {
myTextView.setText("error1");
} catch (SQLException e) {
myTextView.setText("error2");
}
}
EDIT
This is what i found in logcat,,dang,haha so many i did not include the others but what i can understand is it didnt connect to the server or database.
02-11 23:56:13.716 14381-14381/com.example.boneyflesh.connectnapls W/System.err: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
02-11 23:56:13.716 14381-14381/com.example.boneyflesh.connectnapls W/System.err: The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
02-11 23:56:13.716 14381-14381/com.example.boneyflesh.connectnapls W/System.err: at java.lang.reflect.Constructor.newInstance(Native Method)
02-11 23:56:13.716 14381-14381/com.example.boneyflesh.connectnapls W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
02-11 23:56:13.716 14381-14381/com.example.boneyflesh.connectnapls W/System.err: at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:981)
02-12 00:02:48.386 20185-20185/com.example.boneyflesh.connectnapls W/System.err: Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 3306): connect failed: ECONNREFUSED (Connection refused)
02-11 23:25:37.714 2356-2371/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
[ 02-11 23:25:37.717 2356: 2356 D/ ]
HostConnection::get() New Host Connection established 0xaabfc5c0, tid 2356
[ 02-11 23:25:37.718 2356: 2356 W/ ]
Process pipe failed
[ 02-11 23:25:37.755 2356: 2371 D/ ]
HostConnection::get() New Host Connection established 0xaabfc880, tid 2371
02-11 23:25:37.761 2356-2371/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-11 23:25:37.808 2356-2371/? E/EGL_emulation: tid 2371: eglSurfaceAttrib(1165): error 0x3009 (EGL_BAD_MATCH)
Never mind,, i solved it my self tuns out i just need to set my host address to 10.0.2.2 so my url look like this.
private static final String url ="jdbc:mysql://10.0.2.2:3306/db";
As described here

Error in mysql driver: javax.servlet.ServletException: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I'm trying to insert data in my database, but I'm getting this error:
javax.servlet.ServletException: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
here's my jsp file for inserting data in database.
insert.jsp
<%#page import = "java.io.*, java.sql.*, java.util.*"%>
<%#page import = "javax.servlet.http.*, javax.servlet.*"%>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
String connectionURL = "jdbc:mysql://localhost:3306/dbmembers";
Connection connection = null;
PrepareStatament pstatement = null;
Class.forName("com.mysql.jdbc.Driver");
int updateQuery = 0;
if (name!=null && email!=null && uname!=null && pass!=null) {
if (name!="" && email!="uname" && pass!="") {
try{
connection = DriverManager.getConnection(connectionURL, "root","");
String queryString = "INSERT INFO tablemem (Name, Email, Uname, Pass) VALUES (?,?,?,?)";
pstatememt = connection.preparedStatement (queryString);
pstatement.setString(1, name);
pstatement.setString(2, email);
pstatement.setString(3, uname);
pstatement.setString(4, pass);
updateQuery = pstatement.executeUpdate();
if (updateQuery != 0) { %>
<table>
<tr>
<th>Successfully Registered</th>
<th>Login here</th>
</tr>
</table>
<%
}
} catch (Exception ex) {
out.println("Unable to connect to Database");
}
finally {
pstatement.close();
connection.close();
}
}
}
%>
I've already:
place the mysql-connector-java-5.1.39.jar in WEB-INF/lib
added the jar file in eclipse
set the classpath for mysql
But I'm still getting the same error. Did I missed something?
make sure that you have added the connector jar file into the build path
to do so right click on the jar file and click add to build path

Unable to retrieve permissions if file was shared to a group and group is deleted

I'm having an issue with the Google Drive api. If you share a document out to a group, then the group is deleted, the permissions of the file are no longer able to be pulled.
Steps to reproduce.
1. Create document in drive through UI
2. Shared document out to a google internal group
3. Delete group through cPanel.
4. Try to pull permission of file using drive api.
Language : Java
Drive API : v2
Call :
public static void retrievePermissions(Drive serv, ArrayList<Permission> perms, String userEmail, String fileId, String title) throws Exception {
PermissionList permissions = null;
int retry = 5;
while (retry > 0) {
try {
permissions = serv.permissions().list(fileId).execute();
perms.addAll(permissions.getItems());
retry = 0;
}catch(com.google.api.client.googleapis.json.GoogleJsonResponseException je){
je.printStackTrace();
System.err.println("JSON EXCEPTION DOC TITLE :: " + title + " :: user " + userEmail);
retry = 0;
} catch (Exception e) {
retry = retryError(e, retry, printStackTrace);
if (retry == 0)
throw e;
}
}
}
Error Msg :
com.google.api.client.googleapis.json.GoogleJsonResponseException: 500 OK
{
"code" : 500,
"message" : null
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:143)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:114)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:417)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:328)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:449)
at com.promevo.gsd.utils.gData_Drive_Util.retrievePermissions(gData_Drive_Util.java:119)
at com.promevo.gsd.docs.Initial_Run_Docs.doAcls(Initial_Run_Docs.java:254)
at com.promevo.gsd.docs.Initial_Run_Docs.storeDocs(Initial_Run_Docs.java:224)
at com.promevo.gsd.docs.Initial_Run_Docs.pullPageOfDocs(Initial_Run_Docs.java:188)
at com.promevo.gsd.docs.Initial_Run_Docs.doWork(Initial_Run_Docs.java:108)
at com.promevo.gsd.docs.Initial_Run_Docs.run(Initial_Run_Docs.java:99)
at com.google.apphosting.utils.servlet.DeferredTaskServlet.performRequest(DeferredTaskServlet.java:136)
at com.google.apphosting.utils.servlet.DeferredTaskServlet.service(DeferredTaskServlet.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:123)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:61)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.BackendServersFilter.doFilter(BackendServersFilter.java:97)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:94)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:383)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
I am seeing this same behavior using the python libraries, as son as as 'Unknown Group' appears in the permissions list i get 500 error back.