I am using Java(Axis2) to connect .net web service.
I created stub class from WSDL2Java Converter.
Proxy Server : Apache mod_proxy
below all cases are working with the C# code but getting error with the Java(Axis2)
(SSL = true, Proxy = false : Success)
(SSl = false, Proxy = true : Success)
(SSL = true, Proxy = true : Fail (class javax.net.ssl.SSLException))
ServiceStub objStub = new ServiceStub(sWebServiceURL);
objStub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
objStub._getServiceClient().getOptions().setProperty("customCookieID",DEF_COOKIEID);
objStub._getServiceClient().getOptions().setManageSession(true);
objConfigSetting = new DCAServiceConfigSetting();
nSocketTimeout = 30000;
objStub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.SO_TIMEOUT, new Integer(nSocketTimeout));
//Setting the authentication for web service
setServiceAuthentication(objStub, objConnSetting.getAuthenticationInfo());
//Setting Proxy properties
if(objConnSetting.getProxySettingStatus() == true)
{
setProxyProperties(objStub, objConnSetting.getProxySettingInfo());
}
if(objConnSetting.getWebServiceURL().contains("https://"))
{
if(objConnSetting.getWithoutSSLSerCertificateStatus() == true)
{
Protocol objProtocol = new Protocol("https", new MySocketFactory(), 443);
objStub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.CUSTOM_PROTOCOL_HANDLER, objProtocol);
}
// command to set proxy setting
objStub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.PROXY, objProxyProperties);
// Inside MySocketFactory class ----------------------------------------------
public Socket createSocket(final String host,
final int port,
final InetAddress localAddress,
final int localPort,
final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException
{
if (params == null){
throw new IllegalArgumentException("Parameters may not be null");
}
int timeout = params.getConnectionTimeout();
SocketFactory socketfactory = getSSLContext().getSocketFactory();
if (timeout == 0)
{
return socketfactory.createSocket(host, port, localAddress, localPort);
}
else
{
Socket socket = socketfactory.createSocket();
SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
SocketAddress remoteaddr = new InetSocketAddress(host, port);
socket.bind(localaddr);
socket.connect(remoteaddr, timeout);
return socket;
}
}
// Also
private static SSLContext createEasySSLContext()
{
try
{
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[] {new NaiveTrustManager()}, null);
return context;
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
throw new HttpClientError(e.toString());
}
}
Detail Error log
Exception Message: Unrecognized SSL message, plaintext connection?
Stack Trace: org.apache.axis2.AxisFault: Unrecognized SSL message, plaintext connection?
at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
at org.apache.axis2.transport.http.AxisRequestEntity.writeRequest(AxisRequestEntity.java:98)
at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:621)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:193)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:404)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:231)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at WebService.ServiceStub.calWebFunction(ServiceStub.java:1892)
Caused by:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at sun.security.ssl.InputRecord.handleUnknownRecord(Unknown Source)
at sun.security.ssl.InputRecord.read(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at sun.security.ssl.AppOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at java.io.FilterOutputStream.flush(Unknown Source)
at org.apache.axis2.transport.http.AxisRequestEntity.writeRequest(AxisRequestEntity.java:94) ... 20 more
Apache access.log
10.128.43.60 - - [24/Sep/2013:13:49:02 +0900] "\x16\x03\x01" 501 215
Please reply ASAP
Related
I'm creating in Java HttpsURLConnection. I downloaded certificates from website and created file truststore.jks with this certs. My application is getting certs from truststore.jks and connecting to website. And it works... on my PC. But after deploy application on server I got this ugly exception:
Cause: 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
Stack trace:
[sun.security.ssl.Alerts.getSSLException(Unknown Source)
sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
sun.security.ssl.Handshaker.fatalSE(Unknown Source)
sun.security.ssl.Handshaker.fatalSE(Unknown Source)
sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
sun.security.ssl.Handshaker.processLoop(Unknown Source)
sun.security.ssl.Handshaker.process_record(Unknown Source)
sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
I'm creating HttpsURLConnection in ConnectionFactory class, and running connection.getInputStream() method.
ConnectionFactory.java:
public final class ConnectionFactory {
public HttpsURLConnection getHttpsURLConnection(URL url, String trustStorePath, String trustStorePassword)
throws FileTransferWorkerException {
KeyStore keyStore = loadKeyStore(trustStorePath, trustStorePassword);
TrustManagerFactory trustManagerFactory = initTrustManagerFactory(keyStore);
SSLSocketFactory sslSocketFactory = buildSSLSocketFactory(trustManagerFactory);
return buildConnection(url, sslSocketFactory);
}
private KeyStore loadKeyStore(String path, String password) throws FileTransferWorkerException {
KeyStore keystore;
try {
keystore = KeyStore.getInstance("JKS");
} catch (KeyStoreException e) {
throw new FileTransferWorkerException(e);
}
try (FileInputStream fileInputStream = new FileInputStream(path)) {
keystore.load(fileInputStream, password.toCharArray());
} catch (IOException | CertificateException | NoSuchAlgorithmException e) {
throw new FileTransferWorkerException("Can not load keyStore from " + path, e);
}
return keystore;
}
private TrustManagerFactory initTrustManagerFactory(KeyStore keyStore) throws FileTransferWorkerException {
TrustManagerFactory trustManagerFactory;
try {
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
} catch (NoSuchAlgorithmException e) {
throw new FileTransferWorkerException(e);
}
try {
trustManagerFactory.init(keyStore);
} catch (KeyStoreException e) {
throw new FileTransferWorkerException(e);
}
return trustManagerFactory;
}
private SSLSocketFactory buildSSLSocketFactory(TrustManagerFactory trustManagerFactory) throws FileTransferWorkerException {
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
throw new FileTransferWorkerException(e);
}
try {
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
} catch (KeyManagementException e) {
throw new FileTransferWorkerException(e);
}
return sslContext.getSocketFactory();
}
private HttpsURLConnection buildConnection(URL url, SSLSocketFactory sslSocketFactory) throws FileTransferWorkerException {
HttpsURLConnection connection;
try {
connection = (HttpsURLConnection) url.openConnection();
} catch (IOException e) {
throw new FileTransferWorkerException("Can not connect to " + url.getPath(), e);
}
connection.setSSLSocketFactory(sslSocketFactory);
return connection;
}
}
and invoke method:
private void download(URL url, String trustStorePath, String trustStorePassword, File file)
throws IOException, FileTransferWorkerException {
HttpsURLConnection connection = new ConnectionFactory().getHttpsURLConnection(url, trustStorePath, trustStorePassword);
try (ReadableByteChannel reader = Channels.newChannel(connection.getInputStream()){
...
} finally {
connection.disconnect();
}
}
I need to use my truststor.jks file, not cacerts. Do you have any ideas where I made a mistake? Help.
I figured it. Locally I'm connected to my company's network and I have their certificates (because of proxy). But server isn't using proxy and should have real certificates from endpoint server.
I am trying to consume a REST API using Java. however, when I run the code it shows me this exception.
I didn't understand what does it mean, I try to search for the solution but I can't get it :(
this is the connection code:
import javax.ws.rs.core.MediaType;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
public class connectToAPI {
public static void main(String[] args) {
try{
URL url = new URL("https://ip:port/rest/path");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String userpassword = "user:pass";
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","Basic "+
userpassword);
conn.setRequestProperty("Content-Type","application/json");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
int status = 0;
if( null != conn ){
status = conn.getResponseCode();
}
if( status != 0){
System.out.println("status!=0");
if( status == 200 ){
System.out.println("status==200");
//SUCCESS message
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}else if(status == 401){
System.out.println("status==401");
}else if(status == 501){
System.out.println("status==501");
}else if( status == 503){
System.out.println("status==503");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
when I run the code it shows me this exception:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names matching IP address ip 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.getOutputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
at alert.connectToBAM.main(connectToBAM.java:77)
Caused by: java.security.cert.CertificateException: No subject
alternative names matching IP address ip found
at sun.security.util.HostnameChecker.matchIP(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)
... 14 more
I also tried jersey clinet:
javax.ws.rs.client.Client client = ClientBuilder.newClient();
WebTarget target = client.target("https://ip:port/rest/path");
System.out.println(
target.request(MediaType.APPLICATION_JSON).get(String.class));
it shows this error:
Exception in thread "main" javax.ws.rs.ProcessingException:
javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: No subject alternative names
matching IP address ip found
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:284)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:278)
at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:767)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:765)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:428)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:324)
at alert.connectToBAM.main(connectToBAM.java:47)
Any idea? pleaseeee, it is my graduation project :(
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException
Generally these type of exceptions are occurs due to certificate verification issue of the certificate, follow the below steps :
1. Download the certificate from the browser and add it to cacerts file in the jre folder
2. we need to add some java code to verify the certificate using TrustManager.
Code is given below :
public static void trustManager()
{
try
{
TrustManager[] trustAllCerts = new TrustManager[]
{
new X509TrustManager()
{
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
};
//Create an Instance for SSLContext class
SSLContext sc = SSLContext.getInstance("SSL");
//overload init method
sc.init(null, trustAllCerts, new java.security.SecureRandom());
//Use static method setDefaultSSLSocketFactory
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//Create Instance for Hostname verifier and override verify() method
HostnameVerifier allHostsValid = new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1)
{
return true;
}
};
//Verify hostname using static method setDefaultHostnameVerifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
catch(Exception e)
{
e.printStackTrace();
}
}
Whenever you are trying to execute just call this method at first in main method. Hope this will help you :)
I'm developing FTP program on JAVA. I'm using Apache Commons Net Library. My Codes are below.
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class ServerClass {
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
public static void main(String[] args) {
String server = "127.0.0.1";
int port = 80;
String user = "root";
String pass = "root";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Operation failed. Server reply code: " + replyCode);
return;
}
boolean success = ftpClient.login(user, pass);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
return;
} else {
System.out.println("LOGGED IN SERVER");
}
} catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
}
}
But I can't connect my localhost. I want to login my localhost and see my file.
My errors are below.
Oops! Something wrong happened
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:188)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:209)
at com.emrecanoztas.ftp.ServerClass.main(ServerClass.java:22)
can you help me anybody? Thanks!..
Questions:
Is there an FTP server running?
Is there a message in the FTP server log about the connect request?
Does the FTP server allow connections from localhost?
Is the FTP server listening on localhost or should you use the public IP/name of the computer? (check with netstat)
Try the settings below.
String server = "ftp.icm.edu.pl";
int port = 21;
String user = "anonymous";
String pass = "me#nowhere.com";
I'm very confused with this problem. I have HTTPS call. I use JDK 6.0.45. I can't update JDK because the project, that I'm working is very old. Imagine that I have such I code.
HttpGet get = new HttpGet(urlToRead);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(get);
When I was running this code , from main class, I had this type of error:
javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:190)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1747)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1708)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1691)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1222)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1199)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:535)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:403)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:177)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
at hu.barion.BarionServiceWorker.getPOST(BarionServiceWorker.java:52)
at hu.barion.BarionServiceWorker.exchangeMoney(BarionServiceWorker.java:111)
at hu.barion.BarionServiceWorker.main(BarionServiceWorker.java:94)
Caused by: java.lang.RuntimeException: Could not generate DH keypair
at com.sun.net.ssl.internal.ssl.DHCrypt.<init>(DHCrypt.java:114)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverKeyExchange(ClientHandshaker.java:559)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:186)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:943)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1215)
... 13 more
Caused by: java.security.InvalidAlgorithmParameterException: Prime size must be multiple of 64, and can only range from 512 to 1024 (inclusive)
at com.sun.crypto.provider.DHKeyPairGenerator.initialize(DashoA13*..)
at java.security.KeyPairGenerator$Delegate.initialize(KeyPairGenerator.java:627)
at com.sun.net.ssl.internal.ssl.DHCrypt.<init>(DHCrypt.java:107)
... 20 more
OK. I found the solution too. I found this solution in the internet.
Security.addProvider(new BouncyCastleProvider());
That really works well! I have no problems!
But what happens when the call is made from Jboss server?
16:10:48,835 INFO [Server] Root Deployment Filename: jboss-service.xml
16:10:48,836 INFO [Server] Starting General Purpose Architecture (GPA)...
16:10:48,976 INFO [ServerInfo] Java version: 1.6.0_45,Sun Microsystems Inc.
16:10:48,977 INFO [ServerInfo] Java VM: Java HotSpot(TM) 64-Bit Server VM 20.45-b01,Sun Microsystems Inc.
16:10:48,977 INFO [ServerInfo] OS-System: Windows 7 6.1,amd64
16:10:49,140 INFO [Server] Core system initialized
16:10:49,874 INFO [Log4jService$URLWatchTimerTask] Configuring from URL: resource:log4j.xml
16:10:49,914 INFO [WebService] Using RMI server codebase: http://localhost:8083/
16:10:49,977 INFO [NamingService] Started jndi bootstrap jnpPort=1099, rmiPort=1098, backlog=50, bindAddress=localhost/127.0.0.1, Client SocketFactory=null, Server SocketFactory=org.jboss.net.sockets.DefaultSocketFactory#ad093076
16:10:50,871 INFO [Embedded] Catalina naming disabled
16:10:50,979 INFO [Http11Protocol] Initializing Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
16:10:51,169 INFO [Http11Protocol] Initializing Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8443
16:10:51,169 INFO [Catalina] Initialization processed in 281 ms
16:10:51,169 INFO [StandardService] Starting service jboss.web
16:10:51,171 INFO [StandardEngine] Starting Servlet Engine: Apache Tomcat/5.5.9
16:10:51,183 INFO [StandardHost] XML validation disabled
16:10:51,194 INFO [Catalina] Server startup in 25 ms
....
....
....
16:10:54,641 INFO [Http11Protocol] Starting Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
16:10:54,672 INFO [ChannelSocket] JK: ajp13 listening on localhost/127.0.0.1:8009
16:10:54,676 INFO [JkMain] Jk running ID=0 time=0/13 config=null
16:10:54,681 INFO [Http11Protocol] Starting Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8443
16:10:54,687 INFO [Server] JBoss (MX MicroKernel) [4.0.2 (build: CVSTag=JBoss_4_0_2 date=200505022023)] Started in 5s:851ms
....
....
....
javax.net.ssl.SSLException: java.lang.ArrayIndexOutOfBoundsException: 64
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:190)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1747)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1708)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1691)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1222)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1199)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:535)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:403)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:177)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
at hu.barion.BarionServiceWorker.getHTML(BarionServiceWorker.java:70)
at hu.barion.BarionServiceWorker.validateUser(BarionServiceWorker.java:157)
at hu.barion.Services.verifyUser(Services.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.azry.ess.manager.ServiceProxy.invokeAnnotatedMethod(ServiceProxy.java:338)
at com.azry.ess.manager.ServiceProxy.invokeMethod(ServiceProxy.java:279)
at com.azry.ess.manager.ServiceProxy.invokeMethod(ServiceProxy.java:204)
at com.azry.ess.manager.ServiceProxy.execute(ServiceProxy.java:96)
at com.azry.ess.manager.ServiceManagerImpl.executeSevice(ServiceManagerImpl.java:91)
at com.azry.ess.connector.nci.NCI.execute(NCI.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.axis.providers.java.RPCProvider.invokeMethod(RPCProvider.java:388)
at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:283)
at org.apache.axis.providers.java.JavaProvider.invoke(JavaProvider.java:319)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.handlers.soap.SOAPService.invoke(SOAPService.java:453)
at org.apache.axis.server.AxisServer.invoke(AxisServer.java:281)
at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:153)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at ge.bog.commons.log4j.catalina.RequestTimestampValve.invoke(RequestTimestampValve.java:24)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 64
at com.sun.crypto.provider.TlsPrfGenerator.expand(DashoA13*..)
at com.sun.crypto.provider.TlsPrfGenerator.doPRF(DashoA13*..)
at com.sun.crypto.provider.TlsPrfGenerator.doPRF(DashoA13*..)
at com.sun.crypto.provider.TlsMasterSecretGenerator.engineGenerateKey(DashoA13*..)
at javax.crypto.KeyGenerator.generateKey(DashoA13*..)
at com.sun.net.ssl.internal.ssl.Handshaker.calculateMasterSecret(Handshaker.java:753)
at com.sun.net.ssl.internal.ssl.Handshaker.calculateKeys(Handshaker.java:716)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverHelloDone(ClientHandshaker.java:873)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:241)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:943)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1215)
... 59 more
If I add bouncyCasttle provider or not, I have the same error when the call is done via the Jboss. But If I run java file, from main() mehtond, it does not have error.
private Logger logger = Logger.getLogger(SSLExcludeCipherConnectionHelper.class);
private String[] exludedCipherSuites = { "_DHE_", "_DH_" };
private String trustCert = null;
private TrustManagerFactory tmf;
public void setExludedCipherSuites(String[] exludedCipherSuites) {
this.exludedCipherSuites = exludedCipherSuites;
}
public SSLExcludeCipherConnectionHelper(String trustCert) {
super();
this.trustCert = trustCert;
// Security.addProvider(new BouncyCastleProvider());
try {
this.initTrustManager();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void initTrustManager() throws Exception {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new ByteArrayInputStream(trustCert.getBytes());
Certificate ca = null;
try {
ca = cf.generateCertificate(caInput);
logger.debug("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
}
public String get(URL url) throws Exception {
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
SSLSocketFactory osf=context.getSocketFactory();
//SSLParameters params = context.getSupportedSSLParameters();
List<String> enabledCiphers = new ArrayList<String>();
for (String cipher : osf.getSupportedCipherSuites()) {
boolean exclude = false;
if (exludedCipherSuites != null) {
for (int i = 0; i < exludedCipherSuites.length && !exclude; i++) {
exclude = cipher.indexOf(exludedCipherSuites[i]) >= 0;
}
}
if (!exclude) {
enabledCiphers.add(cipher);
}
}
String[] cArray = new String[enabledCiphers.size()];
enabledCiphers.toArray(cArray);
// Tell the URLConnection to use a SocketFactory from our SSLContext
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
urlConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
urlConnection.setRequestMethod("GET");
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(true);
urlConnection.setRequestProperty("Content-Type", "text/html");
SSLSocketFactory sf = context.getSocketFactory();
sf = new DOSSLSocketFactory(sf, cArray);
urlConnection.setSSLSocketFactory(sf);
BufferedReader rd = null;
if (urlConnection.getResponseCode() == 200) {
rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
} else {
rd = new BufferedReader(new InputStreamReader(urlConnection.getErrorStream()));
}
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
return result.toString();
}
public String post(URL url, String json) throws Exception {
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
SSLSocketFactory osf=context.getSocketFactory();
List<String> enabledCiphers = new ArrayList<String>();
for (String cipher : osf.getSupportedCipherSuites()) {
boolean exclude = false;
if (exludedCipherSuites != null) {
for (int i = 0; i < exludedCipherSuites.length && !exclude; i++) {
exclude = cipher.indexOf(exludedCipherSuites[i]) >= 0;
}
}
if (!exclude) {
enabledCiphers.add(cipher);
}
}
String[] cArray = new String[enabledCiphers.size()];
enabledCiphers.toArray(cArray);
// Tell the URLConnection to use a SocketFactory from our SSLContext
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
SSLSocketFactory sf = context.getSocketFactory();
sf = new DOSSLSocketFactory(sf, cArray);
urlConnection.setSSLSocketFactory(sf);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
urlConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(json);
wr.close();
BufferedReader rd = null;
if (urlConnection.getResponseCode() == 200) {
rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
} else {
rd = new BufferedReader(new InputStreamReader(urlConnection.getErrorStream()));
}
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
return result.toString();
}
rivate class DOSSLSocketFactory extends javax.net.ssl.SSLSocketFactory {
private SSLSocketFactory sf = null;
private String[] enabledCiphers = null;
private DOSSLSocketFactory(SSLSocketFactory sf, String[] enabledCiphers) {
super();
this.sf = sf;
this.enabledCiphers = enabledCiphers;
}
private Socket getSocketWithEnabledCiphers(Socket socket) {
if (enabledCiphers != null && socket != null && socket instanceof SSLSocket)
((SSLSocket) socket).setEnabledCipherSuites(enabledCiphers);
return socket;
}
#Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return getSocketWithEnabledCiphers(sf.createSocket(s, host, port, autoClose));
}
#Override
public String[] getDefaultCipherSuites() {
return sf.getDefaultCipherSuites();
}
#Override
public String[] getSupportedCipherSuites() {
if (enabledCiphers == null)
return sf.getSupportedCipherSuites();
else
return enabledCiphers;
}
#Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return getSocketWithEnabledCiphers(sf.createSocket(host, port));
}
#Override
public Socket createSocket(InetAddress address, int port) throws IOException {
return getSocketWithEnabledCiphers(sf.createSocket(address, port));
}
#Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException,
UnknownHostException {
return getSocketWithEnabledCiphers(sf.createSocket(host, port, localAddress, localPort));
}
#Override
public Socket createSocket(InetAddress address, int port, InetAddress localaddress, int localport)
throws IOException {
return getSocketWithEnabledCiphers(sf.createSocket(address, port, localaddress, localport));
}
}
I want to implement a handler in my code to allow a client to automatically connect to a second instance of a server on the same network if the server connected to this client is not responding after 10 seconds. What am I doing wrong??
private static void connectToServer(String serverHostname, int port) throws UnknownHostException, IOException
{
try {
echoSocket = new Socket(serverHostname, 10118);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket
.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Not connected to server: "
+ serverHostname);
System.exit(1);
}
}
public static void main(String[] args) throws IOException {
listServer.add("10.196.113.31");
listServer.add("10.196.113.27");
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
try {
if (args.length > 0)
serverHostname = args[0];
System.out.println("Trying to connect to host " + serverHostname
+ " at port 10118.");
connectToServer(getServer(), 10118);
echoSocket.setSoTimeout(10000);
String userInput;
System.out.print("Input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
if (!echoSocket.isConnected()) connectToServer(serverHostname, 10118);
System.out.println("echo: " + in.readLine());
System.out.print("Input: ");
}
} catch (SocketTimeoutException e) {
NextServer();
connectToServer(getServer(), 10118);
System.out.println("Timeout");
// TODO: handle exception
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
private static void NextServer(){
idServer ++;
}
private static String getServer(){
return listServer.get(idServer);
}
EDIT
When I run the server, then the client, everything is fine. Then I start the second server on another machine on the same network, and try to send text from the same client, the client should automatically detect that the first server is disconnected, connect to the second instance of the server and send the text message. Here is the exception i am getting:
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source) at
sun.nio.cs.StreamDecoder.readBytes(Unknown Source) at
sun.nio.cs.StreamDecoder.implRead(Unknown Source) at
sun.nio.cs.StreamDecoder.read(Unknown Source) at
java.io.InputStreamReader.read(Unknown Source) at
java.io.BufferedReader.fill(Unknown Source) at
java.io.BufferedReader.readLine(Unknown Source) at
java.io.BufferedReader.readLine(Unknown Source) at
Q3.Client.main(Client.java:62)
If you want your client to do something when the server disconnects the connection, you need to do more than just catch SocketTimeoutException. As the stacktrace shows, a dropped connection will result in a generic SocketException being thrown. You should catch this also.
In other words, it looks like you are only handling the case where the initial connection to the server from the client fails; and you are not handling the case where an existing condition is dropped.
If the server is not responding to connect, your setSoTimeout will not cover that case, so make sure you have a timeout in the connection establishment code. Write this:
SocketAddress a = new InetSocketAddress(serverHostname, 10118);
echoSocket = new Socket();
echoSocket.connect(a, 10000);