Skip to content

Instantly share code, notes, and snippets.

@marceloinacio
Created February 14, 2017 02:10
Show Gist options
  • Save marceloinacio/cd96e35087d784e86477893470de5849 to your computer and use it in GitHub Desktop.
Save marceloinacio/cd96e35087d784e86477893470de5849 to your computer and use it in GitHub Desktop.
SSL handshake
import com.google.gson.JsonObject;
import com.pubnub.api.PNConfiguration;
import com.pubnub.api.PubNub;
import com.pubnub.api.callbacks.SubscribeCallback;
import com.pubnub.api.enums.PNLogVerbosity;
import com.pubnub.api.enums.PNReconnectionPolicy;
import com.pubnub.api.models.consumer.PNStatus;
import com.pubnub.api.models.consumer.pubsub.PNMessageResult;
import com.pubnub.api.models.consumer.pubsub.PNPresenceEventResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.SocketFactory;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.*;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class Main {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static final Logger LOG = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
try {
final PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setPublishKey("demo-36");
pnConfiguration.setSubscribeKey("demo-36");
pnConfiguration.setLogVerbosity(PNLogVerbosity.BODY);
pnConfiguration.setReconnectionPolicy(PNReconnectionPolicy.EXPONENTIAL);
LOG.debug("Simple Connection Servlet called!");
SSLContext sslContext = SSLContext.getInstance("TLS");
LOG.debug("SSL context set TLS");
X509TrustManager trustManager = null;
try {
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:"
+ Arrays.toString(trustManagers));
}
trustManager = (X509TrustManager) trustManagers[0];
} catch (GeneralSecurityException e) {
throw new AssertionError(); // The system has no TLS. Just give up.
}
LOG.debug("Trust manager accepted issuers " + trustManager.getAcceptedIssuers());
for (X509Certificate cert : trustManager.getAcceptedIssuers()) {
LOG.debug("Cert details " + cert.toString());
}
// Collect info on default SocketFactory
SocketFactory socketFactoryDefault = SocketFactory.getDefault();
if (socketFactoryDefault != null) {
LOG.debug("A default socket factory has been found! " + socketFactoryDefault);
} else {
LOG.debug("No default socket factory has been found!");
}
sslContext.init(null, new TrustManager[] { trustManager }, null);
LOG.debug("SSContext Cipher Suites: ");
for (String cipherSuite : sslContext.getSupportedSSLParameters().getCipherSuites()) {
LOG.debug("Cipher Suite: " + cipherSuite);
}
LOG.debug("SSContext Protocols List: ");
for (String protocols : sslContext.getSupportedSSLParameters().getProtocols()) {
LOG.debug("Protocols: " + protocols);
}
AlgorithmConstraints algorithmConstraints = sslContext.getSupportedSSLParameters().getAlgorithmConstraints();
LOG.debug("Default Algorithm Constraints: " + algorithmConstraints);
if (sslContext.getSupportedSSLParameters().getServerNames() != null) {
LOG.debug("SSContext SNI server name list: ");
for (SNIServerName sniServerName : sslContext.getSupportedSSLParameters().getServerNames()) {
LOG.debug("SNI server name: " + sniServerName);
}
}
LOG.debug("SSLContext Endpoint indentification Algorithm: " +
sslContext.getSupportedSSLParameters().getEndpointIdentificationAlgorithm());
LOG.debug("SSLContext protocol: " + sslContext.getProtocol());
LOG.debug("SSLContext Provider: " + sslContext.getProvider().getName());
int div = 1000;
int timestamp = (int) ((new Date().getTime()) / div);
pnConfiguration.setSslSocketFactory(sslContext.getSocketFactory());
pnConfiguration.setX509ExtendedTrustManager((X509ExtendedTrustManager)trustManager);
String[] defaultCipherSuites = sslContext.getSocketFactory().getDefaultCipherSuites();
LOG.debug("Default Cipher Suites: ");
for (String cipherSuite : defaultCipherSuites) {
LOG.debug("Cipher Suite : " + cipherSuite);
}
String[] supportedCipherSuites = sslContext.getSocketFactory().getSupportedCipherSuites();
LOG.debug("Supported Cipher Suites : ");
for (String cipherSuite : supportedCipherSuites) {
LOG.debug("Cipher Suite : " + cipherSuite);
}
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
final PubNub pubNub = new PubNub(pnConfiguration);
pubNub.addListener(new SubscribeCallback() {
@Override
public void status(PubNub pubnub, PNStatus status) {
if (status.getOperation() != null) {
switch (status.getOperation()) {
// let's combine unsubscribe and subscribe handling for ease of use
case PNSubscribeOperation:
case PNUnsubscribeOperation:
// note: subscribe statuses never have traditional
// errors, they just have categories to represent the
// different issues or successes that occur as part of subscribe
switch (status.getCategory()) {
case PNConnectedCategory:
// this is expected for a subscribe, this means there is no error or issue whatsoever
case PNReconnectedCategory:
// this usually occurs if subscribe temporarily fails but reconnects. This means
// there was an error but there is no longer any issue
case PNDisconnectedCategory:
// this is the expected category for an unsubscribe. This means there
// was no error in unsubscribing from everything
case PNUnexpectedDisconnectCategory:
// this is usually an issue with the internet connection, this is an error, handle appropriately
case PNAccessDeniedCategory:
// this means that PAM does allow this client to subscribe to this
// channel and channel group configuration. This is another explicit error
default:
// More errors can be directly specified by creating explicit cases for other
// error categories of `PNStatusCategory` such as `PNTimeoutCategory` or `PNMalformedFilterExpressionCategory` or `PNDecryptionErrorCategory`
}
case PNHeartbeatOperation:
// heartbeat operations can in fact have errors, so it is important to check first for an error.
// For more information on how to configure heartbeat notifications through the status
// PNObjectEventListener callback, consult <link to the PNCONFIGURATION heartbeart config>
if (status.isError()) {
// There was an error with the heartbeat operation, handle here
} else {
// heartbeat operation was successful
}
default: {
// Encountered unknown status type
}
}
} else {
// After a reconnection see status.getCategory()
System.out.println(status.getCategory().toString());
}
}
@Override
public void message(PubNub pubnub, PNMessageResult message) {
JsonObject jo = message.getMessage().getAsJsonObject();
int j=0;
}
@Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
}
});
final List<String> channelList = new ArrayList<String>();
channelList.add("ch-24551");
// subscribe channels
pubNub.subscribe().channels(channelList).execute();
System.out.print("Press ENTER");
String s = br.readLine();
}
catch (Exception error) {
// Never go here
System.out.println("I got an exception here: " + error.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment