I want to use JAAS authentication for my Web application. I can't figure out where the error lies. I don't get any error messages but the login part is not working.
I have a Html page (index.html) as front page. When logging in it get username and password and takes it to the servlet.
index.html
<html>
<head>
<title>Login
</title>
</head>
<body>
<br><br>
<center>
<h1>Railway Reservation</h1>
<br><br>
<form action="Authentication" method="post">
User Name:<input type="text" name="user"><br><br>
Password:<input type="password" name="pass"><br><br>
<input type="submit" value="Login">
</form>
</center>
</body>
</html>
Authentication.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import javax.security.auth.login.*;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
public class Authentication extends HttpServlet
{
public Authentication()
{
super();
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("hiii");
String user = request.getParameter("user");
String password = request.getParameter("pass");
pw.println(user + " " + password );
if((user!=null)&&(password!=null))
{
pw.println("if");
CBHandler cbhandler = new CBHandler(user,password);
boolean authFlag = true;
try
{
HttpSession session = request.getSession();
session.setAttribute("username",user);
pw.println("inside try block");
System.setProperty("java.security.auth.login.config","jaas.config");
LoginContext loginContext = new LoginContext("Railway",cbhandler);
loginContext.login();
pw.println("try ");
}
catch(LoginException e)
{
pw.println(e);
e.printStackTrace();
authFlag = false;
pw.println("hello");
}
if(authFlag)
{
pw.println(user + " " + password);
pw.println("Authentication success...");
Connection con = DB.getDBconnection();
if(con!=null)
{
String sql = "select role from login where uname=?";
try
{
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1,user);
ResultSet rs = pst.executeQuery();
rs.next();
String role = rs.getString("role");
if(role.equals("user"))
response.sendRedirect("user.jsp");
else
response.sendRedirect("admin.jsp");
}
catch(Exception e)
{
pw.println(e);
}
}
}
else
pw.println("Authentication failed...");
}
else
{
pw.println("Invalid authentication...");
}
}
}
CBHandler.java
import java.io.*;
import javax.security.auth.callback.*;
public class CBHandler implements CallbackHandler
{
private String user = null;
private String password = null;
public CBHandler(String user,String password)
{
this.user = user;
this.password = password;
}
#Override
public void handle(Callback[] callbackArray) throws IOException,UnsupportedCallbackException
{
int counter = 0;
while(counter < callbackArray.length)
{
if(callbackArray[counter] instanceof NameCallback)
{
NameCallback nameCallback = (NameCallback)callbackArray[counter++];
nameCallback.setName(user);
}
else if(callbackArray[counter] instanceof PasswordCallback)
{
PasswordCallback passwordCallback = (PasswordCallback)callbackArray[counter++];
passwordCallback.setPassword(password.toCharArray());
}
}
}
}
LoginMod.java
import java.util.*;
import java.sql.*;
import java.io.*;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.* ;
import javax.security.auth.spi.LoginModule;
public class LoginMod implements LoginModule
{
private CallbackHandler callbackHandler = null;
private boolean successFlag = false;
#Override
public void initialize(Subject subject, CallbackHandler callbackHandler,Map<String,?> sharedState,Map<String,?> options)
{
this.callbackHandler = callbackHandler;
}
#Override
public boolean login() throws LoginException
{
Callback[] callbackArray = new Callback[2];
callbackArray[0] = new NameCallback("User Name: ");
callbackArray[1] = new PasswordCallback("Password : ",false);
try
{
callbackHandler.handle(callbackArray);
}
catch(IOException e)
{
e.printStackTrace();
}
catch(UnsupportedCallbackException e)
{
e.printStackTrace();
}
String name = ((NameCallback) callbackArray[0]).getName();
String password = new String(((PasswordCallback) callbackArray[1]).getPassword());
if((name.equals("root"))&&(password.equals("root")))
{
System.out.println("auth success");
successFlag = true;
}
else
{
successFlag = false;
throw new FailedLoginException ("auth failed");
}
return successFlag;
}
#Override
public boolean commit() throws LoginException
{
return successFlag;
}
#Override
public boolean abort() throws LoginException
{
return false;
}
#Override
public boolean logout() throws LoginException
{
return false;
}
}
jaas.config
Railway
{
LoginMod required debug=true;
};
When I run this code I get this as Output
hiii root root if inside try block
This is the error I get
HTTP Status 500 – Internal Server Error
Type Exception Report
Message java.io.IOException: jaas.config (No such file or directory)
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
java.lang.SecurityException: java.io.IOException: jaas.config (No such file or directory)
sun.security.provider.ConfigFile$Spi.<init>(Unknown Source)
sun.security.provider.ConfigFile.<init>(Unknown Source)
sun.reflect.GeneratedConstructorAccessor23.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
java.lang.reflect.Constructor.newInstance(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
javax.security.auth.login.Configuration$2.run(Unknown Source)
javax.security.auth.login.Configuration$2.run(Unknown Source)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.login.Configuration.getConfiguration(Unknown Source)
javax.security.auth.login.LoginContext$1.run(Unknown Source)
javax.security.auth.login.LoginContext$1.run(Unknown Source)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.login.LoginContext.init(Unknown Source)
javax.security.auth.login.LoginContext.<init>(Unknown Source)
Authentication.doPost(Authentication.java:37)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.io.IOException: jaas.config (No such file or directory)
sun.security.provider.ConfigFile$Spi.ioException(Unknown Source)
sun.security.provider.ConfigFile$Spi.init(Unknown Source)
sun.security.provider.ConfigFile$Spi.<init>(Unknown Source)
sun.security.provider.ConfigFile.<init>(Unknown Source)
sun.reflect.GeneratedConstructorAccessor23.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
java.lang.reflect.Constructor.newInstance(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
javax.security.auth.login.Configuration$2.run(Unknown Source)
javax.security.auth.login.Configuration$2.run(Unknown Source)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.login.Configuration.getConfiguration(Unknown Source)
javax.security.auth.login.LoginContext$1.run(Unknown Source)
javax.security.auth.login.LoginContext$1.run(Unknown Source)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.login.LoginContext.init(Unknown Source)
javax.security.auth.login.LoginContext.<init>(Unknown Source)
Authentication.doPost(Authentication.java:37)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
The place I was going wrong was giving the location of the configuration file in java.security file, which is present in C:\Program Files\Java\jre1.8.0_77\lib\security\java.security.
When copying the path of the jaas.config file in Windows the path is given with backward slashes( / ), which should be replaced with forward slashes( \ ).
For example, it should be like login.config.url.1=file:D:/mani/java/sample_jaas.config and not as login.config.url.1=file:D:\mani\java\sample_jaas.config
I guess it will be helpful for someone.
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 writing a file reader through REST api, simple code as below:
import domain
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.ssl.HttpsURLConnection;
import java.net.MalformedURLException;
public class Verifier{
public static void main(String args[]) throws IOException
{
URL url = new URL("https://somehostname.xx.xxx.net/somecontent?somequery=number");
try{
HttpsURLConnection http=(HttpsURLConnection) url.openConnection();
int reponse = http.getResponseCode();
//some json processing
//...
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Then I got the error at line
int reponse = http.getResponseCode();
where the error message is:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative DNS name matching somehostname.xx.xxx.net found.
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at domain.main(Verifier.java:39)
Caused by: java.security.cert.CertificateException: No subject alternative DNS name matching somehostname.xx.xxx.net found.
at sun.security.util.HostnameChecker.matchDNS(Unknown Source)
at sun.security.util.HostnameChecker.match(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 15 more
The content from the same site can be retrieved through the chrome browser, without any username or password (but it did show there is a problem with this website's security certificate in IE explorer, not in Chrome, you can continue to get the json content without typing anything).
I am thinking there might be some certificate problem in JAVA/eclipse, maybe? How can I solve it?
Thanks.
SSLContext sc = SSLContext.getInstance( "TLS");
TrustManager[] tmArr = {new X509TrustManager() {
#Override
public void checkClientTrusted(
X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
#Override
public void checkServerTrusted(
X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}};
sc.init(null, tmArr, new SecureRandom());
if (isDetail) {
if (!ValueWidget.isNullOrEmpty(tmArr)) {
System.out.println("first TrustManager:" + tmArr[0]);
}
}
huc = (HttpsURLConnection) url.openConnection();
//解决 javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative DNS name matching apis.map.qq.com found.
((HttpsURLConnection) huc).setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
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).
This error is produced by launching the jar file in cmd with "G:\Orchid\OrchidFX.jar". When launching the application through IntelliJ everything runs just fine. Also, in File->ProjectStructure we have added sqljdbc4.jar to the library.
The Error:
javafx.fxml.LoadException:
file:/G:/Orchid/OrchidFX.jar!/DatabaseSettingsForm.fxml
at javafx.fxml.FXMLLoader.constructLoadException(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at fxproject.ApplicationSplashScreen.loadDatabaseScreen(ApplicationSplashScreen.java:35)
at fxproject.ApplicationSplashScreen.start(ApplicationSplashScreen.java:26)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
... 19 more
Caused by: java.lang.NoClassDefFoundError: com/microsoft/sqlserver/jdbc/SQLServerDataSource
at fxproject.OrchidDataSource.setDataSourceSettings(OrchidDataSource.java:56)
at fxproject.OrchidDataSource.<init>(OrchidDataSource.java:50)
at DataSettingsController.initialize(DataSettingsController.java:34)
... 28 more
Caused by: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDataSource
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 31 more
OrchidDataSource.java:
package fxproject;
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class OrchidDataSource
{
private final String driverType = "jdbc";
private final String dbmsType = "sqlserver";
private String hostname = "192.168.1.173";
private int portNumber = 1433;
private String databaseName = "OrchidDB";
private final String propertyValue = "user=Blah;password=blahblah";
private String username = "blah"; //andrew
private String password = "password";
public String getHostname()
{
return hostname;
}
public int getPortNumber()
{
return portNumber;
}
public String getUsername()
{
return username;
}
public String getPassword()
{
return password;
}
public String getDatabaseName()
{
return databaseName;
}
private SQLServerDataSource dataSource;
private static OrchidDataSource orchidDataSource;
public OrchidDataSource()
{
setDataSourceSettings();
setCurrentDataSource(this);
}
private void setDataSourceSettings()
{
dataSource = new SQLServerDataSource();
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setServerName(hostname);
dataSource.setPortNumber(portNumber);
dataSource.setDatabaseName(databaseName);
}
public void setDataSourceSettings(String username, String password, String hostname, int portNumber, String databaseName)
{
this.username = username;
this.password = password;
this.hostname = hostname;
this.portNumber = portNumber;
this.databaseName = databaseName;
setDataSourceSettings();
}
public void setCurrentDataSource(OrchidDataSource orchidDataSource)
{
this.orchidDataSource = orchidDataSource;
}
public static OrchidDataSource getCurrentDataSource()
{
return orchidDataSource;
}
public Connection getConnection() throws SQLException
{
return dataSource.getConnection();
}
}
DataSettingsController:
package fxproject;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import java.sql.Connection;
public class DataSettingsController
{
public static final String VIEWCONTROLLER_TITLE= "DataSettings";
#FXML
TextField fieldhostname;
#FXML
TextField fieldportnumber;
#FXML
TextField fielddatabasename;
#FXML
TextField fieldusername;
#FXML
PasswordField fieldpassword;
public DataSettingsController()
{
}
#FXML
public void initialize()
{
OrchidDataSource dataSource = new OrchidDataSource();
fieldhostname.setText(dataSource.getHostname());
fieldportnumber.setText(String.valueOf(dataSource.getPortNumber()));
fielddatabasename.setText(dataSource.getDatabaseName());
fieldusername.setText(dataSource.getUsername());
fieldpassword.setText(dataSource.getPassword());
}
#FXML
protected void handleButtonSubmit(ActionEvent e)
{
try
{
OrchidDataSource dataSource = new OrchidDataSource();
dataSource.setDataSourceSettings(fieldusername.getText(),
fieldpassword.getText(),
fieldhostname.getText(),
Integer.parseInt(fieldportnumber.getText()),
fielddatabasename.getText());
Connection connection = OrchidDataSource.getCurrentDataSource().getConnection();
connection.prepareStatement("{call SelectClientStatus()}").executeQuery(); ///low data query to test connection
new MainSystem();
Node source = (Node) e.getSource();
Stage stage = (Stage) source.getScene().getWindow();
stage.close();
}
catch(Exception ae)
{
new OrchidAlertBox("Error", "Database cannot be reached.");
}
}
}
I am trying to connect to MySQL from Java and I get the following error.
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:951)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1717)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1276)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2395)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2428)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2213)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:797)
at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47)
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:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.javawebtutor.jsf.LoginBean.dbData(LoginBean.java:63)
at com.javawebtutor.jsf.LoginBean.checkValidUser(LoginBean.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at org.apache.jasper.el.JspMethodExpression.invoke(JspMethodExpression.java:70)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
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:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2522)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2511)
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)
Exception Occured in the process :java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)"
Thank you for all help, I am very new to this. I am positive the password and username are correct so I am unsure where to go from here. Here is my code for connecting to the database:
package com.javawebtutor.jsf;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name="loginBean")
#SessionScoped
public class LoginBean {
private String userName;
private String password;
private String dbuserName;
private String dbpassword;
Connection connection;
Statement statement;
ResultSet resultSet;
String SQL;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDbuserName() {
return dbuserName;
}
public void setDbuserName(String dbuserName) {
this.dbuserName = dbuserName;
}
public String getDbpassword() {
return dbpassword;
}
public void setDbpassword(String dbpassword) {
this.dbpassword = dbpassword;
}
public void dbData(String userName)
{
Connection con = null;
String conUrl = "jdbc:mysql://localhost:3306/test; user=root; password=pass;";
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(conUrl);
//connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",user = "root","pass");
statement = connection.createStatement();
SQL = "Select * from USER_DETAIL where username like ('" + userName +"')";
resultSet = statement.executeQuery(SQL);
resultSet.next();
dbuserName = resultSet.getString(1).toString();
dbpassword = resultSet.getString(2).toString();
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Exception Occured in the process :" + ex);
}
}
public String checkValidUser()
{
dbData(userName);
if(userName.equalsIgnoreCase(dbuserName))
{
if(password.equals(dbpassword))
return "success";
else
{
return "failure";
}
}
else
{
return "failure";
}
}
}
In MySQL server administration, users are specified with both allowable hostnames and passwords. If the root user was not set up to include localhsot as a client, it will deny logins on the local machine. See this question and its accepted answer for some details.
Can you try like this
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","pass");
As getConnection function requires 3 arguments : url+dbname , username , password.
Your password is wrong it seems.
You can try with empty password given below.
String conUrl = "jdbc:mysql://localhost:3306/test; user=root; password=;";