SSL Server Exception: javax.net.ssl.SSLException - exception

I am creating a SSL Server and Client in Java. The point of the program is to mimic a movie theater program. I can establish the connection but when I attempt to "reserve" a seat the program crashes. I get the following error:
Server aborted: javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
This is my Server Code
// SSL Server
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
public class SSL_Server {
public static void main(String[] args) {
int port = 2018;
System.setProperty("javax.net.ssl.keyStore","mySrvKeystore");
System.setProperty("javax.net.ssl.keyStorePassword","123456");
ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
ServerSocket ssocket = null;
System.out.println("SSL_Server started");
final ExecutorService threadPool = Executors.newCachedThreadPool();
try {
ssocket = ssocketFactory.createServerSocket(port);
InetAddress myIP =InetAddress.getLocalHost();
System.out.println(myIP.getHostAddress());
while(true){
Socket aClient = ssocket.accept();
//create a new thread for every client
threadPool.submit(new SSL_ClientHandler(aClient));
}
}
catch(Exception e) {
System.err.println("Server aborted:" + e);
} finally {
try{
ssocket.close();
} catch (Exception e){
System.err.println("could not close connection properly" + e);
}
}
System.out.println("connection was closed successfully");
}
}
The following is my client code
//SSL Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocketFactory;
public class TCP_Client {
public static void main(String[] args) throws IOException{
// SSL_Client newClient = new SSL_Client();
// Lock lock = new ReentrantLock();
boolean validInput = false;
BufferedReader din;
PrintStream pout;
int port = 2018;
BufferedReader stdinp = new BufferedReader(new InputStreamReader(System.in));
String line = "done";
StringTokenizer st;
String hostname;
String task = "done";
if(args.length>0)
hostname = args[0];
else
hostname = "localhost";
SocketFactory socketFactory = SSLSocketFactory.getDefault();
//Socket socket = socketFactory.createSocket(hostname, port);
while(true)
{
try{
//read input
while(!validInput)
{
System.out.println("Please enter a valid command or 'done' to finish.");
line = stdinp.readLine();
st = new StringTokenizer(line);
task = st.nextToken();
if(task.equals("reserve") || task.equals("search") || task.equals("delete") || task.equals("getinfo") || task.equals("done"))
{
validInput =true;
break;
}
System.out.println("Invalid command. Please enter another command or 'done' to escape.");
}
if(task.equals("done"))
{
break;
}
validInput = false;//reset for next line read in
//create a new socket every time
//Socket socket = new Socket(hostname, port);
Socket socket = socketFactory.createSocket(hostname, port);
din = new BufferedReader (new InputStreamReader (socket.getInputStream()));
pout = new PrintStream (socket.getOutputStream());
pout.println(line);
pout.flush();
//print out response from server
System.out.println(din.readLine());
} catch (Exception e){
System.err.println("Server aborted: " + e);
}
}
}
}

"Unable to find valid certification path to requested target" means that your truststore doesn't trust the server certificate. Import it into your truststore, or have it signed by a recognized CA.

Related

Azure Webapp is not updating Azure database for mysql

I have a web application that needs to communicate with azure mysql database. I have included the connection string for jdbc as given in the portal and also modified the connection parameters to allow all inbound IPs. Still the database wont update with the input data. What should I do more?
My connection string is:
String url ="jdbc:mysql://upes.mysql.database.azure.com:3306/students? useSSL=true&requireSSL=false";
Connection myDbConn = DriverManager.getConnection(url, "****", "****");
My controller servlet code:
package Controller;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.util.Base64;
import java.sql.*;
import Model.*;
#WebServlet(name = "controller")
#MultipartConfig(maxFileSize = 16177215)
public class controller extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String v1 = request.getParameter("email");
String v2 = request.getParameter("password");
String v4 = request.getParameter("act");
String v5 = request.getParameter("name");
if(v4.equals("Register"))
{
request.getRequestDispatcher("/SignUp.jsp").forward(request, response);
}
if (v4.equals("SignUp"))
{
Part filePart = request.getPart("photo");
String email="";
String name="";
String base64Image="";
InputStream image= filePart.getInputStream();
newuser r = new newuser();
r.register(v5, v1, v2, image);
try{
PreparedStatement statement = null;
ResultSet resultSet = null;
//Class.forName("com.mysql.jdbc.Driver");
//Connection con = DriverManager.getConnection("jdbc:mysql://upes.mysql.database.azure.com:3306/students?useSSL=true&requireSSL=false", "****", "****");
String url ="jdbc:mysql://upes.mysql.database.azure.com:3306/students?useSSL=true&requireSSL=false";
Connection myDbConn = DriverManager.getConnection(url, "****", "****");
statement = myDbConn.prepareStatement("select * from studentdata where email=?");
statement.setString(1, v1);
resultSet=statement.executeQuery();
while(resultSet.next()) {
email=resultSet.getString("email");
name=resultSet.getString("name");
Blob blob = resultSet.getBlob("photo");
InputStream inputStream = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] imageBytes = outputStream.toByteArray();
base64Image = Base64.getEncoder().encodeToString(imageBytes);
inputStream.close();
outputStream.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
request.setAttribute("name", name);
request.setAttribute("email", email);
request.setAttribute("image",base64Image);
request.getRequestDispatcher("/UserAccount.jsp").forward(request, response);
}
if(v4.equals("Log In"))
{
request.getRequestDispatcher("/SignIn.jsp").forward(request, response);
}
if(v4.equals("SignIn"))
{
String email="";
String name="";
String base64Image="";
Check c= new Check();
String res=c.checker(v1,v2);
if(res.equals("SUCCESS")) {
try{
PreparedStatement statement = null;
ResultSet resultSet = null;
//sClass.forName("com.mysql.jdbc.Driver");
//Connection myDbConn = DriverManager.getConnection("jdbc:mysql://upes.mysql.database.azure.com:3306/students?useSSL=true&requireSSL=false", "****", "****");
String url ="jdbc:mysql://upes.mysql.database.azure.com:3306/students?useSSL=true&requireSSL=false";
Connection myDbConn = DriverManager.getConnection(url, "****", "****");
statement = myDbConn.prepareStatement("select * from studentdata where email=?");
statement.setString(1, v1);
resultSet=statement.executeQuery();
while(resultSet.next()) {
email=resultSet.getString("email");
name=resultSet.getString("name");
Blob blob = resultSet.getBlob("photo");
InputStream inputStream = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] imageBytes = outputStream.toByteArray();
base64Image = Base64.getEncoder().encodeToString(imageBytes);
inputStream.close();
outputStream.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
request.setAttribute("name", name);
request.setAttribute("email", email);
request.setAttribute("image",base64Image);
request.getRequestDispatcher("/UserAccount.jsp").forward(request, response);
}
}
if(v4.equals("Sign Out"))
{
request.getRequestDispatcher("/welcome.jsp").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}```
If you haven't turned the "Allow access to Azure services" option to 'ON', kindly turn it On and then verify the connection.
To do this > On the MySQL server blade > open 'Settings' blade >> click 'Connection Security' > Select ON in "Allow access to Azure services", then Save.
I believe when you mentioned 'modified the connection parameters to allow all inbound IPs' - You have added/allowed Firewall rules for App Service 'outbound IP address' list to MySQL 'Connection security'.
Note that Azure Database for MySQL has SSL enabled by default. If your application is not using SSL to connect to the database, then you need to disable SSL on the MySQL server.
Just to isolate, also please to review the connections via "Diagnose and solve problems'

MySQL JDBC connection stop working

String url = "jdbc:mysql://localhost:3306/mysql";
String user = "root";
String pass = "root1";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, pass);
System.out.println("Connected to database");
} catch (Exception e) {
System.out.println(e);
System.out.println("Could not connect to database");
}
Password should be "root". The program does not display the message in the catch block and stops working. Can anyone tell me what happens?
[UPDATE]
I apologise I asked a bad question. The problem is already solved, Thanks. This helps to properly check whether the connection exists.
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
There are three different ways to connect to SQL data base as shown in below code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class MySQLConnectExample {
public static void main(String[] args) {
// creates three different Connection objects
Connection conn1 = null;
Connection conn2 = null;
Connection conn3 = null;
try {
// connect way #1
String url1 = "jdbc:mysql://localhost:3306/test1";
String user = "root";
String password = "secret";
conn1 = DriverManager.getConnection(url1, user, password);
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
// connect way #2
String url2 = "jdbc:mysql://localhost:3306/test2?user=root&password=secret";
conn2 = DriverManager.getConnection(url2);
if (conn2 != null) {
System.out.println("Connected to the database test2");
}
// connect way #3
String url3 = "jdbc:mysql://localhost:3306/test3";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "secret");
conn3 = DriverManager.getConnection(url3, info);
if (conn3 != null) {
System.out.println("Connected to the database test3");
}
} catch (SQLException ex) {
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
}
}

Creating a JSON file from a url

Hi guys I have a problem creating a JSON file from a google url that i have. This is my code that im using.
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadUrl {
public String readUrl(String strUrl) throws IOException, InterruptedException {
Log.d("URLS = ",strUrl);
Thread.sleep(2000);
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
}
It works fine when i throw a url that looks like this into it.
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7207523,-73.383851&radius=4828&type=bar&key=MYKEY
But when i try and throw a url that looks like this into it.
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJe3AmoGsr6IkRuWcK1LAh-DE&key=MYKEY
I get an error: D/GooglePlacesReadTask: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
I dont know how i fix this. Any help?
Aah
you did not mention this is in android,
I presume this because you said ,
android.os.NetworkOnMainThreadException
in your comment
Android does not allow time consuming tasks on main thread,
use AsyncTask to call your function or use plain old java thread
Network on main thread exception comes when you run a networking operation on main thread .
Generally AsyncTask is used for these works but if you want to use the same code you written Just add..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Must issue a STARTTLS command first java

I am using JavaMail and smtp (gmail), here's my code :
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Email {
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
public static void main(String args[]) throws AddressException,
MessagingException {
Email javaEmail = new Email();
javaEmail.setMailServerProperties();
javaEmail.createEmailMessage();
javaEmail.sendEmail();
}
public void setMailServerProperties() {
String emailPort = "587";//gmail's smtp port
emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", emailPort);
emailProperties.put("mail.smtp.auth", "true");
emailProperties.put("mail.smtp.starttls.enable", "true");
}
public void createEmailMessage() throws AddressException,
MessagingException {
String[] toEmails = { "to#gmail.com" };
String emailSubject = "Java Email";
String emailBody = "This is an email sent by JavaMail api.";
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
for (int i = 0; i < toEmails.length; i++) {
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
}
emailMessage.setSubject(emailSubject);
emailMessage.setContent(emailBody, "text/html");//for a html email
//emailMessage.setText(emailBody);// for a text email
}
public void sendEmail() throws AddressException, MessagingException {
String emailHost = "smtp.gmail.com";
String fromUser = "yourusername";//just the id alone without #gmail.com
String fromUserEmailPassword = "your_password";
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromUser, fromUserEmailPassword);
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
transport.close();
System.out.println("Email sent successfully.");
}
}
Error Message :
Exception in thread "main" javax.mail.MessagingException: 530 5.7.0
Must issue a STARTTLS command first. n80sm23847952pfi.25 - gsmtp
at
com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1020)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:716)
at
com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:388)
at com.mail.Email.sendEmail(Email.java:68) at
com.mail.Email.main(Email.java:26)
Could you try changing this line:
Transport t = session.getTransport("smtps");
You'll have to supply the appropriate username and password needed by
your mail server. Note that you can change the protocol to "smtps" to
make a secure connection over SSL.
The complete information here: http://www.oracle.com/technetwork/java/javamail/faq/index.html#gmail
In my case, the above issue occured when I use ibm-was-*.jar. And it got resolve when I switch the jar to Javax.mail-version.jar (version is a number like 1.5.5).

Getting a MAC address from the IP's retrieved from a ping sweep

Basically I have 2 bits of code one will do a ping sweep of a network range and then one will retrieve a MAC address from a given IP.
What I would like to do is incorporate these two pieces of code so when the ping sweep is performed it shows the MAC address in the output next to the IP addresses.
The MAC address retrieval code is as follows...
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test118;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Test118 {
public static String command;
public String ip = "192.168.0.4";
Test118() {
command = "arp -a " + ip;
}
public void viewMac() {
String process = null;
String mac[] = new String[5];
String rmac[] = new String[10];
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
int i = 0;
while ((line = bufferedreader.readLine()) != null) {
mac[i] = line;
i++;
}
rmac = mac[3].split(" ");
System.out.println(rmac[2]);
} catch (Exception e) {
System.out.println("mac cant find");
}
}
public static void main(String[] args) throws Exception {
Test118 r = new Test118();
r.viewMac();
}
}
The ping sweep is as follows...
package pingstestnew;
import java.io.IOException;
import java.net.InetAddress;
public class NetworkPing {
public static void main(String[] args) throws IOException {
InetAddress localhost = InetAddress.getLocalHost();
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
for (int i = 142; i <= 145; i++)
{
ip[3] = (byte)i;
InetAddress address = InetAddress.getByAddress(ip);
if (address.isReachable(1000))
{
System.out.println(address + " Host is reachable");
}
else if (!address.getHostAddress().equals(address.getHostName()))
{
System.out.println(address + " Hostname Resolved, Host is reachable");
}
else
{
System.out.println(address + " Host Unreachable");
}
}
}
}