woensdag 13 juli 2016

autocomplete with javascript

introduction

Every now and then as a java programmer you run into a java script piece. I have to admit that java script and myself are not good friends for ages now. Every time I have to do something with java script I cry in silence.  So I started a nice Java project to work out some java script stuff and see If I could deal with it (call me a masochist). One of the things that kept me wandering around for a while was how to build a autocomplete that  calls a service. I found a lot of examples with prefab list. After digging around a lot I found an example that connected to a service. It was not working so i started trying and finally i got it working.


The solution

//jquery libraries needed.
<script src="<c:url value="https://code.jquery.com/jquery-3.0.0.min.js" />" 
type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/
jquery-ui.css">
// the html label and input that gonna function as autocomplete.
// the css class is coming from jquer ui. 
<div class="ui-widget">
  <td><label for="autocompleteChars">Autocomplete: </label></td>
  <td><input id="autocompleteChars"></td>
</div>

// The array that is gonna contain the service result.
var autoCompleteContent;
$( function() {
    //coupling the autocomplete to the html input.
    $("#autocompleteChars").autocomplete({
        source: function( request, response ) {
            $.post({
                        url: "<the url to the service>" 
+ document.getElementById('autocompleteChars').value,
                        dataType: "json",
                        // if the request was successfull.
                        success: function( data ) {
                            response( $.map( data, function( item ) {

                                //reïnitializing the array to empty the previous.
                                autoCompleteContent = new Array();
                                //looping through the results from the service. 
                                for(index=0; index<item.length; index++) {
                                    //creating the layout of an autocomplet line.
                                    var autoComplete =  item[index]['element1'] 
                                     + '  ' + item[index]['element2'];
                                    // adding it to the array
                                    autoCompleteContent.push(autoComplete);
                                }
                                //return the list as desired to the html input.
                                return autoCompleteContent;
                            }));
                        }
                    })
                     // if the request fails.
                    .fail(function(response) {
                        console.log('Error: ' + response.responseText);
                    });
        },
        minLength: 1    });
});

Conclusion

The prove I found in fighting this little piece of code was that I found out
 that I am still the plumber in the backend. I just love building stuff in 
the backend and sometimes just popup at the frontend to do a trick or two but 
to move silently back again. I am happy that I finished this piece and made 
it work. There are many ways to rome even in the javascript world.
You find some of those roads by google. But with the most of them you never get 
to Rome. I hope that I can help some other java developers with this, that just 
as me, allways struggle with javascript.

Have fun!

dinsdag 21 juni 2016

Alternative implementation of an Interface with lambda

Introduction

Normally to have an implementation of an Interface is extra work 
  1. Create a class
  2. Implement the Interface
  3. Implementing the  method(s)
I always thought of this as the boring part except implementing the method(s)
 So I was fooling a bit around with Lambda's in Java and figured a way of interface implementation without creating an extra class for it. I thought that this way might be nice when the implementation of the Interface happens  only ones. Like in Spring when you use Inversion of Control.
Lets have a look at how it could be done with Lambda's

The solution to the problem 

First of all you create the Interface:

public interface WorkerInterface {
  //The method to implement 
  void doSomeWork();
}


Secondary the class that is having the interface and the implemented method:

public class LambdaTest {
    //The method that executes the Interfaces method.
    private void execute(WorkerInterface worker) {
        worker.doSomeWork();
    }

    //Just the plain old main to start up this class.
    public static void main(String [] args) {
        LambdaTest lambdaTest = new LambdaTest();
        lambdaTest.run();
    }

    private void run() {
        //A list with names to start this examples
        List<String> names = new ArrayList<>();
        names.add("Test1");
        names.add("Test2");
        names.add("Test3");
        //The lambda way to do a for loop
        //With the first arrow you assign name to the execute method.
         names.forEach(name ->
        //With the second arrow you assign the execute method.
        // to the implementation you had in mind.
        execute( () ->
       System.out.println(name) ));
    }
}

Conclusion
As you can see this works quite easy. By using a double assignment one assign the data to the execute method and the other to assign the execute method to the implementation, it is possible to make an Interface method execute something without an extra class file.
Have fun!

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!