zondag 31 januari 2016

Apache HttpClient connect

Introduction

 As sometimes needed you want one service to communicate with the other without interference of the frontend. One of the ways to do that is to setup a connection through the apache httpClient. In our project we allready did that but with an old version of te HttpClient. Therefore we needed to upgrade to the latest version. At this point in time it is 4.5.1. The only downside of this client is, that it is still not upgraded to HTTP 2.0. read the specs here. But we did it anyway in the hope that the coming version would use the HTTP 2.0 specifications. 

The solutution

This solution is not giving you the whole shabang  but it gives you a good idea howto setup a basic configuration that works and will help you to setup through a proxy or not.

//The maven part:
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.4</version>
</dependency>


//If you in need of a proxy set it up like this with ofcourse the right adress and 
//port.
HttpHost proxy = new HttpHost("proxy", 8080, "http");
// Configure the request with timeouts and in this case a proxy. 
//If you don't need a proxy you can leave that particular part out 
RequestConfig config = RequestConfig.custom()
        .setConnectionRequestTimeout(30000)
        .setSocketTimeout(30000)
        .setProxy(proxy)
        .build();
//Instead of using the HttpMethod in the old version we now 
//should use the HttpGet or the HttpPost HttpGet httpget = 
new HttpGet("http://yourservice/getEverything");
httpget.setConfig(config);
//This is one of the ways to setup a HttpClient.
//there are many more ways as you will find in these examples. 
HttpClient client = HttpClientBuilder.create()
        .build();
// retrieving the response as HttpResponse and printout
//the http statusHttpResponse response = client.execute(httpget);
System.out.println(response.getStatusLine());


Conclusion

It is not so hard to set this up once you have an idea of what you need to do. I been searching the internet for a some examples. The sad story of this search was that there a lot of old examples out there. I only hope that this library is soon updated to http 2.0.

woensdag 13 januari 2016

retrieve the end date from a certificate




 Introduction

This week we had a really nice challenge. As most companies we use certificates. They help us to keep the connections secure. The downside of certificates is that they need to be renewed now and then. It is so easy to notice an expired certificate by undesirable behaviour of the connection. If this happens  your already to late. To be ahead of this, we decided to do a check up on this particular certificate. 

The solution
To start of all you need an object of the type Certificate. In this mather I start with an certificate, which needed to be read from disk:   

//Take the file from disk as an inputStream using the classloader for this.
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("testCertificate/testCertificate.pem");

//getting the CertificateFactory of the type x.509 
//(X509Certificate is the only child of Certificate)
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
Certificate certificate = certFactory.generateCertificate(inputStream);

// setting up the keystore with an default type. You can also use:
//getInstance(String type,Provider provider)
//getInstance(String type, String provider)
// Type could be pkcs12 or jks these are archive file formats for storing many //cryptography objects as a single file.
// types could be SUN or bc (bouncy castle).
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

//adding the certificate to the keystore with an alias
keyStore.setCertificateEntry("alias", certificate);

// creating the date object outside the scope of the try we can return it later.
Date notAfter = null;

try {
  // initializing the keystore with null to prevent exceptions to be thrown later on.
  keyStore.load(null);

//checking if the keystore has an alias and retrieve the first one.
 //(we only have one). If you know the alias you can loose this piece of code.
    if(keyStore.aliases().hasMoreElements()) {
        Enumeration<String> aliasses = keyStore.aliases();
        String alias = aliasses.nextElement(); 

// cast it to the X509Certificate That has the getNotAfter method. Certificate
//doesn't have that.
X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);

 // assigning the date to the end date of the certificate.
notAfter = certificate.getNotAfter();
    }
} catch (KeyStoreException ke) {
    log.error("could not read keystore or certificate", ke);
} catch (CertificateException ce) {
    log.error("no certifications in keystore", ce);
} catch (NoSuchAlgorithmException nse) {
    log.error("wrong algorythm for certificate.", nse);
} catch (IOException ioe) {
    log.error("could not read certificate.", ioe);
}

// returning the end date.
return notAfter;

Conclusion

To understand what is happening in this particular piece of code acquires some time and dedication. The fun part starts when you understand it. I still enjoy the moments where I crack a case like this and understand why it is needed to  be done like this. I hope you enjoy it also.
Have fun!



dinsdag 12 januari 2016

testing log statements

Introduction

Testing can sometimes make your head spin. For example when a method is a void and you are not allowed to use powermock. 
The thing with a method like that, is that it is not returning an Object on which you can test on. 
If you are lucky it might have a parameter that changes during the execution of the method. 
Sometimes it has a log statement based on a Exception or on an event captured in an if statement, that happened during execution.  
That gives also opportunities. Let me show how.

The solution
 
For working with log files the best thing to do is approach them with log appenders. 
//We start with a mock appender: 
@Mockprivate Appender mockAppender;
//Creating a rootlogger to hold all the appenders. 
ch.qos.logback.classic.Logger root = 
(ch.qos.logback.classic.Logger) LoggerFactory.getLogger 
(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
 
 // appending the ArgumentMatcher to the mockAppender. 
Mockito.verify(mockAppender).doAppend(Mockito.argThat 
(new ArgumentMatcher<Object>() { 
//implementing the matches method to see if the
// log text appears in the log file 
@Overridepublic boolean matches(final Object argument) {
return ((LoggingEvent) argument).getFormattedMessage()
//The text we want to search. 
.contains("test logging text that should be found");}}));
 

The conclusion
Void methods could be still a call for an asperine when it comes to testing. There are some helpful methods I believe that this is one of them. I used it this time to test a method that checked if an certificate was expired. This way I could pump up the test coverage of my code.
Have fun!