Creation of an HTTPS server in Java - java

I have been trying to create a simple HTTPS server in my application. I am able to get the server running while also finishing the 'SSL context creation' without errors( where I have included the System.out.println("SSL context created ...\n");).
However, I am unable to connect to it through a browser or even a java written client. a java written client returns a NoHttpResponseException when I attempt to connect to this application.
" Exception in thread "main" org.apache.http.NoHttpResponseException: localhost:8000 failed to respond "
So, is it possible to point out what I am missing in the below code? Thanks
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsParameters;
import com.sun.net.httpserver.HttpsServer;
import java.io.FileInputStream;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManagerFactory;
public class HTTPSserver {
public static void main(String[] args) throws Exception {
char[] password = "SSLauthentication".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fileInput = new FileInputStream("C:\\Files\\Certificates\\clientkeystore");
ks.load(fileInput, password);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, password);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
SSLContext ssl = SSLContext.getInstance("TLS");
ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
HttpsServer server = HttpsServer.create(new InetSocketAddress(8000), 0);
server.setHttpsConfigurator (new HttpsConfigurator(ssl)
{
#Override
public void configure (HttpsParameters params)
{
try
{
SSLContext c = getSSLContext();
SSLParameters sslparams = c.getDefaultSSLParameters();
params.setSSLParameters(sslparams);
System.out.println("SSL context created ...\n");
}
catch(Exception e2)
{
System.out.println("Invalid parameter ...\n");
e2.printStackTrace();
}
}
});
server.createContext("/test", new MyHandler());
server.setExecutor(null);
server.start();
}
static class MyHandler implements HttpHandler {
#Override
public void handle(HttpExchange HTTPmessage) throws IOException {
if("GET".equals(HTTPmessage.getRequestMethod()))
{
String response = "This is aaa response";
HTTPmessage.sendResponseHeaders(200, response.length());
OutputStream os = HTTPmessage.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
}

Related

getLocalCertificates() return null

I'm trying to write a simple ssl server socket and client socket program. first i get some real certificate and then i used the first code to generate keystore for it. then i wrote server and client code so my server use that keystore as server certificate but no certificate sent during connection and session.getLocalCertificates() only return null
my keystore generating code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.security.KeyStore;
import java.security.cert.CertPath;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
public class MainClass {
public static void main(String args[]) throws Exception {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
List mylist = new ArrayList();
FileInputStream in = new FileInputStream("C:\\Users\\nima\\Downloads\\72315359_example.com.cert");
Certificate cr = cf.generateCertificate(in);
mylist.add(cr);
CertPath cp = cf.generateCertPath(mylist);
System.out.println(cp);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
List cplist = cp.getCertificates();
Object[] o = cplist.toArray();
for (int i = 0; i < o.length; i++) {
X509Certificate c = (X509Certificate) o[i];
ks.setCertificateEntry("my" + i, c);
}
FileOutputStream output = new FileOutputStream("C:\\Users\\nima\\Downloads\\test.dat");
ks.store(output, "mypass".toCharArray());
output.close();
}
}
my server code:
import java.io.PrintStream;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
public class MainClass {
public static void main(String args[]) throws Exception {
System.setProperty("javax.net.ssl.keyStore", "C:\\Users\\nima\\Downloads\\test.dat");
System.setProperty("javax.net.ssl.keyStorePassword", "mypass");
SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
ServerSocket ss = ssf.createServerSocket(5432);
while (true) {
Socket s = ss.accept();
SSLSession session = ((SSLSocket) s).getSession();
Certificate[] cchain2 = session.getLocalCertificates();
for (int i = 0; i < cchain2.length; i++) {
System.out.println(((X509Certificate) cchain2[i]).getSubjectDN());
}
System.out.println("Peer host is " + session.getPeerHost());
System.out.println("Cipher is " + session.getCipherSuite());
System.out.println("Protocol is " + session.getProtocol());
System.out.println("ID is " + new BigInteger(session.getId()));
System.out.println("Session created in " + session.getCreationTime());
System.out.println("Session accessed in " + session.getLastAccessedTime());
PrintStream out = new PrintStream(s.getOutputStream());
out.println("Hi");
out.close();
s.close();
}
}
}
my client code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class MainClass {
public static void main(String args[]) throws Exception {
System.setProperty("javax.net.ssl.trustStore", "C:\\Users\\nima\\Downloads\\test.dat");
SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
Socket s = ssf.createSocket("127.0.0.1", 5432);
SSLSession session = ((SSLSocket) s).getSession();
Certificate[] cchain = session.getPeerCertificates();
System.out.println("The Certificates used by peer");
for (int i = 0; i < cchain.length; i++) {
System.out.println(((X509Certificate) cchain[i]).getSubjectDN());
}
System.out.println("Peer host is " + session.getPeerHost());
System.out.println("Cipher is " + session.getCipherSuite());
System.out.println("Protocol is " + session.getProtocol());
System.out.println("ID is " + new BigInteger(session.getId()));
System.out.println("Session created in " + session.getCreationTime());
System.out.println("Session accessed in " + session.getLastAccessedTime());
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String x = in.readLine();
System.out.println(x);
in.close();
}
}
my server code is from here and in both server and client side i get null from getLocalCertificates. It's also possible that all of my code would be wrong.
(From comments, expanded slightly)
If SSLSocket.getSession() is called before the handshake is done, it tries to do it, but if the handshake fails getSession() swallows the exception and just returns a 'nullSession' object which doesn't have the data a real session object would. Either (1) set sysprop javax.net.debug=ssl (at startup, usually on commandline with -D) and look at what it logs to see what is wrong with your handshake or (2) explicitly call ((SSLSocket)s).startHandshake() (which in spite of the name actually runs the handshake to completion, successful or not) and see what it throws.
In particular if you use the keystore file created by the first code shown, that contains only a certificate (trustedCertEntry) NOT a privateKeyEntry (with both privatekey and certificate/chain) as is necessary and required for an SSL/TLS server to use any of the common and default-enabled suites; this error will usually manifest, somewhat confusingly, as a handshake failure with 'no cipher[suite] in common' or 'no cipher[suite] overlap'.
That second part (SSL/TLS server without a privatekey doesn't work) has been asked and answered many times, but I don't recall any dupes that also include the 'getSession masks the error' part.

WebSocket server get client certificate onOpen

I have a simple ServerEndpoint running on WildFly 10, which is configured as wss with mutual TLS, so client certificate required. I have no problems in connecting to endpoint, so the mutual authentication is correctly done, but I can't access client certificate in onOpen method. I am trying to do it using getUserPrincipal(), I'm always getting null.
I need to get client certificate for authorization purposes.
import java.io.IOException;
import java.security.Principal;
import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint(value = "/test", configurator = GetHttpSessionConfigurator.class)
public class TestWebSocketEndPoint {
private Session wsSession;
private HttpSession httpSession;
#OnOpen
public void onOpen(Session session, EndpointConfig config){
this.wsSession = session;
this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
Principal userPrincipal = session.getUserPrincipal();
System.out.println(session.getId() + " has opened a connection");
try {
session.getBasicRemote().sendText("Connection Established");
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* When a user sends a message to the server, this method will intercept the message
* and allow us to react to it. For now the message is read as a String.
*/
#OnMessage
public void onMessage(String message, Session session){
System.out.println("Message from " + session.getId() + ": " + message);
try {
session.getBasicRemote().sendText(message);
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* The user closes the connection.
*
* Note: you can't send messages to the client from this method
*/
#OnClose
public void onClose(Session session){
System.out.println("Session " +session.getId()+" has ended");
}
}
GetHttpSessionConfigurator:
import java.security.Principal;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {
#Override
public void modifyHandshake(ServerEndpointConfig config,
HandshakeRequest request,
HandshakeResponse response)
{
HttpSession httpSession = (HttpSession)request.getHttpSession();
Map<String, List<String>> map = request.getParameterMap();
Principal principal = request.getUserPrincipal();
config.getUserProperties().put(HttpSession.class.getName(),httpSession);
}
}
RequestListener:
import java.security.Principal;
import java.security.cert.X509Certificate;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
#WebListener
public class RequestListener implements ServletRequestListener {
public void requestDestroyed(ServletRequestEvent sre) {
// TODO Auto-generated method stub
}
public void requestInitialized(ServletRequestEvent sre) {
((HttpServletRequest) sre.getServletRequest()).getSession();
Principal p = ((HttpServletRequest) sre.getServletRequest()).getUserPrincipal();
boolean secure = ((HttpServletRequest) sre.getServletRequest()).isSecure();
String authType = ((HttpServletRequest) sre.getServletRequest()).getAuthType();
X509Certificate[] certs = (X509Certificate[]) ((HttpServletRequest) sre.getServletRequest()).getAttribute("javax.servlet.request.X509Certificate");
}
}
The websocket client is a standalone application using TooTallNate/java-websocket and connecting securely:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.Enumeration;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.java_websocket.WebSocketImpl;
public class TestClient {
private static final Log log = LogFactory.getLog(TestClient.class);
public static void main(String[] args) throws URISyntaxException {
WebSocketImpl.DEBUG = true;
WSRAClient wsRaClient = new WSRAClient(new URI("wss://localhost:8443/TestWebSocket-0.0.1-SNAPSHOT/test"));
String keystoreFile = "keystore.p12";
String keystorePassword = "keystore";
String truststoreFile = "truststore.jks";
String truststorePassword = "truststore";
try {
SSLContext ssl = SSLContext.getInstance("TLSv1.2");
log.info("Configuring SSL keystore");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
log.debug("Loading keystore");
store.load(new FileInputStream(keystoreFile), keystorePassword.toCharArray());
log.debug("Number of keystore certificates: " + store.size());
Enumeration<String> enumeration = store.aliases();
while(enumeration.hasMoreElements()) {
String alias = enumeration.nextElement();
log.debug("alias name: " + alias);
Certificate certificate = store.getCertificate(alias);
log.debug(certificate.toString());
}
kmf.init(store, keystorePassword.toCharArray());
KeyManager[] keyManagers = new KeyManager[1];
keyManagers = kmf.getKeyManagers();
log.info("Configuring SSL truststore");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
log.debug("Loading truststore");
truststore.load(new FileInputStream(truststoreFile), truststorePassword.toCharArray());
log.debug("Number of truststore certificates: " + truststore.size());
enumeration = truststore.aliases();
while(enumeration.hasMoreElements()) {
String alias = (String)enumeration.nextElement();
log.debug("alias name: " + alias);
Certificate certificate = truststore.getCertificate(alias);
log.debug(certificate.toString());
}
tmf.init(truststore);
TrustManager[] trustManagers = tmf.getTrustManagers();
ssl.init(keyManagers, trustManagers, new SecureRandom());
SSLSocketFactory factory = ssl.getSocketFactory();// (SSLSocketFactory) SSLSocketFactory.getDefault();
wsRaClient.setSocket(factory.createSocket());
wsRaClient.connectBlocking();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ( true ) {
String line = reader.readLine();
if(line.equals("close")) {
wsRaClient.close();
} else {
wsRaClient.send(line);
}
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (KeyStoreException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (CertificateException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (KeyManagementException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (InterruptedException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
}
}
}
See : Accessing HttpServletRequest properties within a WebSocket #ServerEndpoint
Create servlet filter on URL pattern matching websocket handshake request.
In filter, get request attribute of interest and put it in session before continuing chain.
Finally get it from the session which is in turn just available via handshake request

javax.net.ssl.SSLException: unexpected_message

We're trying to make secure http communication between client an server.
The server provided the certificates, we took them, install them and we start running, the point is to exchange an exact number of messages simultaneously between the client and server consecutively, the problem that's driving us crazy is that between the requests, at SSLHANDSHAKE we get randomly the exception javax.net.ssl.SSLException: Received fatal alert: unexpected_message exactly at ServerHello handshake phase, and i don't know how or why this is happening while it keeps working fine for 98% of the other requests.
it crashes at step 2.
Transporter.java : This is the class responsible for sending and receiving the data.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyStore;
import java.util.ResourceBundle;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
public class Transporter {
private static ResourceBundle resource = ResourceBundle.getBundle("resourece_00");
private static final String keystore = resource.getString("server_keystore");
private static final String truststore = resource.getString("server_truststore");
private static final String keypass = resource.getString("server_keystore_pwd");
private static final String trustpass = resource.getString("server_truststore_pwd");
// secure channel variables
private static SSLSocketFactory sslSocketFactory = null;
public Transporter() {
// setupSocketFactory();
}
static {
try {
String protocol = "TLS";
String type = "JKS";
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
// create and initialize an SSLContext object
SSLContext sslContext = SSLContext.getInstance(protocol);
sslContext.init(getKeyManagers(type, algorithm), getTrustManagers(type, trustAlgorithm), null);
// obtain the SSLSocketFactory from the SSLContext
sslSocketFactory = sslContext.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
private static KeyStore getStore(String type, String filename, String pwd) throws Exception {
KeyStore ks = KeyStore.getInstance(type);
InputStream istream = null;
try {
File ksfile = new File(filename);
istream = new FileInputStream(ksfile);
ks.load(istream, pwd != null ? pwd.toCharArray() : null);
} finally {
if (istream != null) {
istream.close();
}
}
return ks;
}
private static KeyManager[] getKeyManagers(String type, String algorithm) throws Exception {
KeyStore ks = getStore(type, keystore, keypass);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, keypass.toCharArray());
return kmf.getKeyManagers();
}
private static TrustManager[] getTrustManagers(String type, String algorithm) throws Exception {
KeyStore ts = getStore(type, truststore, trustpass);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
tmf.init(ts);
return tmf.getTrustManagers();
}
public String sendToVD(String msg, String urll, Long timeOut) {
byte[] bytes = msg.getBytes();
HttpsURLConnection sconn = null;
URL url = null;
OutputStream out = null;
BufferedReader read = null;
String recu = null;
try {
url = new URL(urll);
sconn = (HttpsURLConnection) url.openConnection();
sconn.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession sslSession) {
return true;
}
});
sconn.setSSLSocketFactory(sslSocketFactory);
// sconn.setReadTimeout((timeOut.intValue()) * 1000);// set timeout
sconn.setRequestMethod("POST");
sconn.addRequestProperty("Content-Length", "" + bytes.length);
sconn.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
sconn.setDoOutput(true);
sconn.setDoInput(true);
// send POST data
// This is the crash location
out = sconn.getOutputStream();
// OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
out.write(bytes);
out.flush();
// logger.info("flush!!!!!!!!!!!!!");
// out.close();
read = new BufferedReader(new InputStreamReader(sconn.getInputStream()));
String query = null;
recu = read.readLine();
while ((query = read.readLine()) != null) {
recu += query;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// close all connections here
if (out != null)
out.close();
if (read != null)
read.close();
if (sconn != null)
sconn.disconnect();
} catch (Exception ce) {
}
}
return recu;
}
}
The function sendToVD() does the main work of the exchange between the client and the server.
At Client-End :
A web application with JSF managing the front layer, spring managing the beans life cycle, the communication entry to the client is assured by Servlets.
The client is deployed in a RedHat Linux machine, all TLS_VERSIONS are enbaled, JDK_8.
At Server-Side: i can't post the detailed information about the target URL for security measures, but it follows the following pattern https://ip:port/path, and it supports TLS_v1.2.
Hope you can help me out.

Java to Android Code

I have coded this client ssl code for java which works great and sends the wave file to a server. I am trying now to change or use this code on Android but I am having problems doing so. The questions that I have are things such as:
How do I set the pathStore and trustStoreFile(which directories are these on the android)?
Where do I upload the certificate file to(trustStoreFile) ?
Are there any settings that I need to configure?
Is this code what I need to use to accomplish the task of sending the wav file to the server that is listening?
Thanks so much !
Please Help !
Here is the ssl client code in :
package admir.network.ssl.client;
import android.provider.Settings;
import java.io.*;
import java.net.*;
import java.security.*;
import javax.net.ssl.SSLSocketFactory;
import org.apache.commons.io.IOUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.TrustManager;
//import com.sun.net.ssl.SSLContext;
//import com.sun.net.ssl.TrustManagerFactory;
//import com.sun.net.ssl.TrustManager;
public class test2 {
private static final String HOST = "X.X.X.X";
private static final int PORT = 5000;
String pwd = System.getProperty("user.dir");
final static String pathToStores = System.setProperty("user.dir","user.dir"+"/java/admir.network.ssl.client/");
final static String trustStoreFile = "cert.jks" ; // filename
public String app = System.setProperty("user.dir",pwd);
public static void main(String[] args) throws Exception {
String trustFileName = pathToStores + "/" + trustStoreFile;
char[] passphrase = "xxxxx".toCharArray();
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream(trustFileName), passphrase);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(keystore);
SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = tmf.getTrustManagers();
context.init(null, trustManagers, null);
SSLSocketFactory sf = context.getSocketFactory();
Socket s = sf.createSocket(HOST, PORT);
String FILE_TO_SEND = ""+ System.getProperty("user.dir")+"/"+"src"+"/"+"Voice 005.wav"+"";
File soundFile = AudioUtil.getSoundFile(FILE_TO_SEND);
if (s.isBound()){
OutputStream out = s.getOutputStream();
InputStream in = new FileInputStream(soundFile);
IOUtils.copy(in, out);
System.out.println("Done Sending.");
out.close();
}
s.close();
}
}

Soap Server WSDL viewable in browser, but wont load any functions in SoapUI

I just recently installed BoneCP on my soap server to prevent too many mysql connections being made when people hit the soap server. Before I switched over to boneCP the soap server was working, however now after I've installed boneCP I can see the WSDL if I go directly to the link for it, but when I load that same link into soapUI it loads the wsdl but does not show any functions at all. My code is below:
package testing;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.xml.ws.Endpoint;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;
import com.sun.net.httpserver.*;
#WebService
public class test {
static BoneCP connectionPool = null;
static Connection con = null;
#WebMethod
public String login(#WebParam(name="username")String username,#WebParam(name="password") String password) throws SQLException {
con = connectionPool.getConnection();
Statement stmt = null;
String query = " CALL authorize_user('" + username + "','" + password + "')";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String login = rs.getString("au_result");
if (login != null){
con.close();
return login;
}
else {
con.close();
return "Login Failed";
}
}
} catch (SQLException e) {
System.out.println("Error: " + e);
} finally {
if (stmt != null) {
stmt.close();
}
}
con.close();
return "Login Failed";
}
public static void main(String[] args) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException, NoSuchProviderException {
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
e.printStackTrace();
return;
}
try{
BoneCPConfig config = new BoneCPConfig();
config.setJdbcUrl("jdbc:mysql://localhost:" + port + "/test");
config.setUsername(username);
config.setPassword(password);
config.setMinConnectionsPerPartition(5);
config.setMaxConnectionsPerPartition(10);
config.setPartitionCount(1);
connectionPool = new BoneCP(config);
if(con != null){
System.out.println("Connection successful");
}
}catch(Exception e){
e.printStackTrace();
}
test test = new test();
Endpoint endpoint = Endpoint.create(test);
String uri = "/testing";
String keystoreFile = "keystore.jks";
String keyPass = "test_pass";
int port = 8080;
SSLContext ssl = SSLContext.getInstance("TLS");
KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore store = KeyStore.getInstance("JKS");
store.load(new FileInputStream(keystoreFile),keyPass.toCharArray());
keyFactory.init(store, keyPass.toCharArray());
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustFactory.init(store);
ssl.init(keyFactory.getKeyManagers(),
trustFactory.getTrustManagers(), new SecureRandom());
HttpsConfigurator configurator = new HttpsConfigurator(ssl);
HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress(port), 50);
System.out.println("https server: " + httpsServer.getAddress());
httpsServer.setHttpsConfigurator(configurator);
com.sun.net.httpserver.HttpContext httpContext = httpsServer.createContext(uri);
httpsServer.start();
endpoint.publish(httpContext);
}
}
This code is basically exactly the same as the working code I was using a week ago except for the boneCP section in the main method.
For anyone who is intersted and may have this problem in the future: I found the error within my code, it wasn't actually realated to boneCP at all, instead of had to do with the #webparam(name = "") code on some of the other functions in my code. These had spaces in the name, and so were causing problems within the soap server.

Categories

Resources