I try to connect to mysql database on my Java EE project but i get an error and I do not know where is the problem.
And this is SERVLET, CLASS AND ERRORS
The Java EE Servlet:
package com.hopital.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.hopital.database.Recup_Insert;
import com.hopital.forms.Connections;
#WebServlet("/hopital")
public class hopital extends HttpServlet {
private static final long serialVersionUID = 1L;
public hopital() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//extrait les cookies
Cookie[] cookies= request.getCookies();
if(cookies != null){
for(Cookie cookie: cookies){
if(cookie.getName().equals("login")){
request.setAttribute("login", cookie.getValue());
}
}
}
//session
HttpSession session= request.getSession();
String login= (String) session.getAttribute("login");
request.setAttribute("login", login);
//extrait les chambers
Recup_Insert tableChamber= new Recup_Insert();
request.setAttribute("chambres",tableChamber.recup_chmabre());
this.getServletContext().getRequestDispatcher("/WEB-INF/home.jsp").forward(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//verification de champs
Connections form= new Connections();
form.verifie(request);
request.setAttribute("form", form);
//stocke les champs entre
String login=request.getParameter("login");
String pass=request.getParameter("pass");
//cree un cookies
Cookie cookie=new Cookie("login",login);
cookie.setMaxAge(60*60*24*30);
response.addCookie(cookie);
// cree un session sur login et mot de passe
HttpSession session= request.getSession();
session.setAttribute("login", login);
session.setAttribute("pass", pass);
this.getServletContext().getRequestDispatcher("/WEB-INF/home.jsp").forward(request,response);
}
}
My class that contain the database connexion:
package com.hopital.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import com.hopital.projet.chamber;
public class Recup_Insert {
public List<chamber> recup_chmabre(){
List<chamber> chambers= new ArrayList<chamber>();
//charger les drivers
try{
Class.forName("com.mysql.jdbc.Driver");
}catch( ClassNotFoundException e){
}
//Connexion
Connection connexion=null;
Statement statement=null;
ResultSet resultat = null;
try {
connexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/hopital", "root", "3636");
statement= connexion.createStatement();
resultat= statement.executeQuery("SELECT * FROM CHAMBER;");
while(resultat.next()){
int etage = resultat.getInt("etage");
int ID_pat = resultat.getInt("ID_pat");
int num = resultat.getInt("num");
int nom_lits = resultat.getInt("nom_lits");
int occupee = resultat.getInt("occupee");
chamber chamber = new chamber();
chamber.setEtage(etage);
chamber.setID_pat(ID_pat);
chamber.setNum(num);
chamber.setOccupee(occupee);
chamber.setNom_lits(nom_lits);
chambers.add(chamber);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try{
if(resultat != null)resultat.close();
if(statement != null)statement.close();
if(connexion != null)connexion.close();
}catch(SQLException ignore){
}
}
return chambers;
}
}
AND THIS IS THE ERRORS AFTER RUNING:
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:983)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:339)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2252)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2285)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2084)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.hopital.database.Recup_Insert.recup_chmabre(Recup_Insert.java:29)
at com.hopital.servlet.hopital.doGet(hopital.java:44)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:214)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:298)
... 39 more
Check connection URL and credentials. Try connecting with the same parameters using some SQL client.
You got this error because you cannot connect to database.
Most probably you didn't start you server. Check either it running or not, then double check port where it is running. Also check spelling on table name in database it should be "hopital".
Check For mysql-connector-java-5.1.21-bin.jar file added to Properties=>libraries=>
if not then add external jar=>mysql-connector-java-5.1.21-bin.jar
also check port number of tomcat server and mysql.
Related
I am trying to send an email in my JavaFX application
Everything works perfect, email is sent to Reciepent, i get no exceptions and no errors when i run it in IDE (InteliJ) but when I run the app outside Intelij it doesn't work.
I made simple registration form which saves data from fields into my database:
String username;
String password;
String email;
Random rd = new Random();
int ID;
public void registerUser(javafx.event.ActionEvent ab) {
username = textUser.getText();
password = textPass.getText();
email = textEmail.getText();
ID = rd.nextInt(999999999);
Connection connectt = null;
try {
Class.forName("org.sqlite.JDBC");
connectt = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\barte\\OneDrive\\Desktop\\sqlite databases\\PRODUCTS\\Products.db");
String s = "INSERT INTO Users(Username,Password,Email,UserID) VALUES (?,?,?,?) ";
PreparedStatement registera = connectt.prepareStatement(s);
registera.setString(1, username);
registera.setString(2, password);
registera.setString(3, email);
registera.setInt(4, ID);
System.out.println(username);
System.out.println(password);
System.out.println(email);
registera.executeUpdate();
System.out.println("Added to Database");
sendMail();
registerr.setStyle("-fx-background-color: #69ff59;");
registerr.setText("Check Your MailBox");
registerr.setOnMouseClicked(event -> {
registerr.setText("Email Has been sent");
});
textUser.setText(null);
textEmail.setText(null);
textPass.setText(null);
regiPane.setVisible(false);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
And here is code for sending email:
public void sendMail() throws MessagingException {
String USER_NAME = "stoc****";
String from = USER_NAME;
String PASSWORD = "************";
String pass = PASSWORD;
String RECIPT = textEmail.getText();
String TOPIC = "Welcome " + username + "!";
String BODY = "Dear user! " +
"You can sign into StockFX by your ID/Username and password" +
"User ID: " + ID + "\n" + "Password: " + password + "\n" +
"We would like to thank you for using our services now and in future!";
String[] to = {RECIPT};
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"****", PASSWORD);
}
});
MimeMessage message = new MimeMessage(session);
try {
try {
message.setFrom(new InternetAddress(from));
} catch (MessagingException e) {
e.printStackTrace();
}
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for (int i = 0; i < to.length; i++) {
try {
toAddress[i] = new InternetAddress(to[i]);
} catch (AddressException e) {
e.printStackTrace();
}
}
for (int i = 0; i < toAddress.length; i++) {
try {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
} catch (MessagingException e) {
e.printStackTrace();
}
}
try {
message.setSubject(TOPIC);
} catch (MessagingException e) {
e.printStackTrace();
}
try {
message.setText(BODY);
} catch (MessagingException e) {
e.printStackTrace();
}
try {
message.saveChanges();
} catch (MessagingException e) {
e.printStackTrace();
}
registerr.setStyle("-fx-background-color: #69ff59;");
registerr.setText("You can now log in");
registerr.setDisable(false);
textUser.setText(null);
textEmail.setText(null);
textPass.setText(null);
regiPane.setVisible(false);
Transport transport = session.getTransport("smtp");
System.out.println("get protocl");
transport.connect(host, from, pass);
System.out.println("get host,from and password");
transport.sendMessage(message, message.getAllRecipients());
System.out.println("get recipients");
transport.close();
System.out.println("close");
System.out.println("Email Sent Successfully!");
} finally {
System.out.println("Complete Process");
}
}
Everything works fine inside InteliJ but void sendEmail won't work in runable jar
I am new to Java mail.
Imports:
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.*;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
import java.util.Random;
import java.util.ResourceBundle;
This class is Controller Class
And this is the main Class:
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.io.IOException;
public class Main extends Application {
#Override
public void start(Stage UI) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("DashBoard.fxml"));
UI.setTitle("DIREXT SCANNER (DEMO VER 0.5)");
UI.setScene(new Scene(root, 800, 600));
UI.initStyle(StageStyle.UNDECORATED);
UI.setResizable(false);
UI.show();
UI.setFullScreenExitHint("Press 'ESC' to exit full screen");
}
public static void main(String[] args){
launch(args);
}
}
I tried rebuilding project, delete and add libraries again but the same result
Did anybody elese encountered the same problem?
Is it IDE related or am I missing imports or methods?
I tried to look for similar question on forums, I have already fixed few things, as before runable jar wouldn't run at all.
If question exist please can someone provide the link.
edit
this is the error i get when i run jar from PowerShell:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(Unknown Source)
at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.base/javafx.event.Event.fireEvent(Unknown Source)
at javafx.graphics/javafx.scene.Node.fireEvent(Unknown Source)
at javafx.controls/javafx.scene.control.Button.fire(Unknown Source)
at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(Unknown Source)
at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.base/javafx.event.Event.fireEvent(Unknown Source)
at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.graphics/javafx.scene.Scene$MouseHandler.access$1300(Unknown Source)
at javafx.graphics/javafx.scene.Scene.processMouseEvent(Unknown Source)
at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at javafx.graphics/com.sun.glass.ui.View.notifyMouse(Unknown Source)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.reflect.Trampoline.invoke(Unknown Source)
at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(Unknown Source)
at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(Unknown Source)
... 52 more
Caused by: java.lang.NoClassDefFoundError: javax/activation/DataHandler
at sample.DashBoardController.registerUser(DashBoardController.java:321)
... 62 more
Caused by: java.lang.ClassNotFoundException: javax.activation.DataHandler
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
... 63 more
I found solution thanks to all your help
What i did, in project structure, I deleted all artifact, modules and libraries and add everything back again then rebuild the project then build the artifact and I also did set my project folder as Source Root and it worked.
If you are using External Libraries So The problem Sometimes Happens in the Path of this Libraries When you extract to jar File , Simple Solution that Sometimes Work is to create new project and create new Files As the Old Project And move them
I am trying to make a project on Servlets using JDBC. But there are some persistent errors in the error log like java.lang.Class.forName(Unknown Source), java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source), java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source), java.lang.Thread.run(Unknown Source) etc. How can I solve such errors from happening?
I am using Apache Tomcat v7.0, mySQL Community Server v5.7 and Eclipse IDE.
This my error log:
java.lang.ClassNotFoundException: com.mysql.driver.JDBC
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Register.register(Register.java:10)
at RegisterServlet.doPost(RegisterServlet.java:34)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
This is the JDBC file code(Register.java):
import java.sql.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Register {
public static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
public static final Pattern VALID_PHONE_NUMBER_REGEX = Pattern.compile("[7-9][0-9]\\d{9}"); // ,Pattern.CASE_INSENSITIVE);
public static int register(String name,String user,String pass,String cpass,String email, String phone,String city,String state) throws ClassNotFoundException{
int status=0;
try{
Class.forName("com.mysql.driver.JDBC");
Connection con=DriverManager.getConnection("jdbc:sqlite:localhost:8080/Diary.db");
System.out.println("Database connected successfully!!");
PreparedStatement ps=con.prepareStatement("INSERT INTO Trial(name, user, pass, email, phone, city, state, authorized) values(?,?,?,?,?,?,?,?)");
if(pass!=null && cpass!=null && phone!=null && name!=null && user!=null && city!=null && state!=null){
Matcher matcher1 = VALID_EMAIL_ADDRESS_REGEX .matcher(email);
Matcher matcher2 = VALID_PHONE_NUMBER_REGEX .matcher(phone);
if((pass==cpass) && (matcher1.find()) && (matcher2.find())){
ps.setString(1,name);
ps.setString(2,user);
ps.setString(3,pass);
ps.setString(4,email);
ps.setString(5,phone);
ps.setString(6,city);
ps.setString(7,state);
ps.setString(8,"yes");
status=ps.executeUpdate();
}
else{
status = 0;
}
}
}catch(SQLException e){e.getMessage();}
return status;
}
}
This is my servlet (RegisterSevlet.java):
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
int status;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String name=req.getParameter("name");
String user=req.getParameter("user");
String pass=req.getParameter("pass");
String cpass=req.getParameter("cpass");
String email=req.getParameter("email");
String phone=req.getParameter("phone");
String city=req.getParameter("city");
String state=req.getParameter("state");
try {
status = Register.register(name, user, pass, cpass, email, phone, city, state);
if(status > 0){
out.print("<p>You are successfully registered!</p>");
req.getRequestDispatcher("login.html").include(req, res);
}
else if(status == 0){
out.println("<p>Enter the information correctly!</p>");
res.sendRedirect("register.html");
}
req.getRequestDispatcher("#").include(req, res);
out.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
`Class.forName()`
throws ClassNotFoundException
You need to include multicatch statement for that (same catch for SQLException and ClassNotFoundException)
You can modify your catch statement to this:
catch (ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}
Try this. You can use a multicatch statement wherever you need to catch multiple exceptions.
This exception is thrown whenever a class existed at compile time but not at run time.
Please check that at runtime ur classpath is correct and you are pointing to the library in question (in ur case the mysql connector jar).
I have a problem while I try to access big query through Java API from a Java application in my desktop. Code is:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.BigqueryScopes;
import com.google.api.services.bigquery.model.GetQueryResultsResponse;
import com.google.api.services.bigquery.model.QueryRequest;
import com.google.api.services.bigquery.model.QueryResponse;
import com.google.api.services.bigquery.model.TableCell;
import com.google.api.services.bigquery.model.TableRow;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
public class GettingStarted {
public static Bigquery createAuthorizedClient() throws IOException {
HttpTransport transport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
if (credential.createScopedRequired()) {
credential = credential.createScoped(BigqueryScopes.all());
}
return new Bigquery.Builder(transport, jsonFactory, credential)
.setApplicationName("Bigquery Samples")
.build();
}
private static List<TableRow> executeQuery(String querySql, Bigquery bigquery, String projectId)
throws IOException {
QueryResponse query =
bigquery.jobs().query(projectId, new QueryRequest().setQuery(querySql)).execute();
// Execute it
GetQueryResultsResponse queryResult =
bigquery
.jobs()
.getQueryResults(
query.getJobReference().getProjectId(), query.getJobReference().getJobId())
.execute();
return queryResult.getRows();
}
private static void printResults(List<TableRow> rows) {
System.out.print("\nQuery Results:\n------------\n");
for (TableRow row : rows) {
for (TableCell field : row.getF()) {
System.out.printf("%-50s", field.getV());
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
Scanner sc;
if (args.length == 0) {
sc = new Scanner(System.in);
} else {
sc = new Scanner(args[0]);
}
String projectId="glassy-land-140915";
Bigquery bigquery = createAuthorizedClient();
List<TableRow> rows =
executeQuery(
"SELECT corpus as unique_words "
+ "FROM [bigquery-public-data:samples.shakespeare] LIMIT 10",
bigquery,
projectId);
printResults(rows);
}
}
Exception
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:77)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:283)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:868)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at GettingStarted.executeQuery(GettingStarted.java:38)
at GettingStarted.main(GettingStarted.java:73)
You could also use a proxy with you java client
java -Dhttp.proxyHost= -Dhttp.proxyPort= …. -jar you_bg_client.jar
problem was firewall in the network preventing from accessing google cloud. Used a different network and fetched the results.
I am trying to copy file through FTPClient and testing in my local system
My code is like this with my IPv4 address as input for host
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPUploader {
FTPClient ftp = null;
public FTPUploader(String host, String user, String pwd) throws Exception{
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(host);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(user, pwd);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
}
public void uploadFile(String localFileFullName, String fileName, String hostDir)
throws Exception {
try(InputStream input = new FileInputStream(new File(localFileFullName))){
this.ftp.storeFile(hostDir + fileName, input);
}
}
public void disconnect(){
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException f) {
// DO NOTHING
}
}
}
public static void main(String[] args) {
try{
System.out.println("Start");
FTPUploader ftpUploader = new FTPUploader("10.66.***.***", "username", "password");
ftpUploader.uploadFile("D:/Venkatesh.pptx", "65.pptx", "C:/Users/VENKATESH/Desktop");
ftpUploader.disconnect();
System.out.println("Done");
}catch(Exception exception){
exception.printStackTrace();
}
}
}
Now by this, Iam getting the following Exception
Start
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:168)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:189)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:278)
at fileTransfer.FTPUploader.<init>(FTPUploader.java:21)
at fileTransfer.FTPUploader.main(FTPUploader.java:51)
What is the mistake iam doing ????
The program is absolutely fine.
Problem is at the server side.
Exception here is :
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
The error is because of wrong credentials ( or ) the server is not started.
The file is transferred after restarting the server :)
I am trying to get response from below REST api. when I open that URL in browser, I gets xml repsonse from server. but when I am trying to get the same using java program I am getting below exception
IOEXCeption
java.net.UnknownHostException: rxnav.nlm.nih.gov
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at com.test.demo.RestConnector.run(RestConnector.java:22)
at java.lang.Thread.run(Unknown Source)
Pls help me regarding this
below is the code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class RestConnector implements Runnable{
#Override
public void run() {
String URLString = "http://rxnav.nlm.nih.gov/REST/classes?src=MESH";
try {
URL url = new URL(URLString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
if(connection.getResponseCode() != 200){
System.out.println("Failed to connect:"+connection.getResponseCode());
System.out.println("Response Message:"+connection.getResponseMessage());
}
System.out.println("I am here ");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line ;
while((line = reader.readLine()) != null){
System.out.println(line);
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOEXCeption");
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread t = new Thread(new RestConnector());
t.start();
}
}
1) The error clearly says "can't resolve hostname".
2) Q: Does your AndroidManifest.xml grant Internet permissions? Make sure it contains this line:
<uses-permission android:name="android.permission.INTERNET" />
3) Q: is this a real device, or an emulator? If the latter, consider recreating your AVD. Believe it or not, that can sometimes help: Android java.net.UnknownHostException: Host is unresolved.
4) Finally, here are some other tips - including proxy server configuration - that might help:
http://eliasbland.wordpress.com/2011/02/22/java-net-unknownhostexception-on-android-a-list-of-possible-causes/