dinsdag 25 september 2018

The builder pattern in Kotlin


Introduction

The most of you are probably familiar with the builder pattern. I used this pattern a couple of times in Java later on with the @Builder annotation from the Lombok project. I am aware of the fact that the annotations of Lombok project are also usable in Kotlin. This is just for fun or when you are not using Lombok for what reason suits you. 

the code

For this example I used a data class called Address. I am aware that it lacks some fields but that is not important in this explanation. Ok, lets get down to it:


data class Address(
        //The class members that will contain the data.
        val addressLine1: String,
        val addressLine2: String = "",
        val city: String,
        val zip: String,
    //The builder class 
    class Builder {
        private lateinit var addressLine1: String
        private var addressLine2: String = ""
        private var city: String = ""
        private var state: String = ""
        //The assignment to the class members.
        fun addressLine1(addressLine1: String) = apply { this.addressLine1 = addressLine1 }
        fun addressLine2(addressLine2: String) = apply { this.addressLine2 = addressLine2 }
        fun city(city: String) = apply { this.city = city }
        fun country(country: String) = apply { this.country = country }

        //The build method we need to call.
        fun build() = Address(
                addressLine1,
                addressLine2,
                city,
                state,
                country
        )
    }
     
       //The instanciation of the Adress class. 
       val address:Address = Address
                // calling the builder class.
                 .Builder()
                 //filling the fields with data.
                .addressLine1("Address1")
                .addressLine2("Address2")
                .city("City")
                .country("Country")
                //calling the build method
                .build()

        // Voila data
        println(address.addressLine1)

Conclusion

As allways, with a new way you have to get used to the fact that things are different. If you are new to Kotlin this might look magical to you. At least it did to me. Now I am working with Kotlin for a while I am used to the syntax. I am capable of doing stuff in Kotlin I did not think I would ever do. 

Have fun!
 

dinsdag 13 februari 2018

rpc call to bitcoind


Introduction

Lately, in the news you can find a lot of material about bitcoins or the technique behind it. I have been reading a lot about this the last couple of months. It made me curious howto connect to the bitcoind myself. It must be possible too connect to the daemon and get that information yourself. I know, curiousity killed the cat. But I am still alive. Lets dive into the code and see what we should do.

The example

So lets get started with the fun shall we? The surprising part is that it was less difficult then I thought it would be. Too get the right parts of all the different examples together and make it work was the hardest part.
First of all we need the bitcoind. We can install the daemon and ask if it is still alive. That is why I prefer too install bitcoin-qt. This has an interface where you can see some things like if it is running on testnet. Install it like:

sudo add-apt-repository ppa:bitcoin/bitcoin 
sudo apt-get update
sudo apt-get install bitcoin-qt
place in the ~/.bitcoin folder the file bitcoin.conf. The content should be als followed to run on testnet:
## bitcoin.conf configuration file. Lines beginning with # are comments.
### Uncomment and edit options you wish to use.

## JSON-RPC options (for controlling a running bitcoin-qt/bitcoind process)

# server=1 tells Bitcoin to accept JSON-RPC commands.
server=1

# You must set rpcuser and rpcpassword to secure the JSON-RPC api
# You should create your own new random password.
# The username and password MUST NOT be the same.

rpcuser=user
rpcpassword=password

# How many seconds bitcoin will wait for a complete RPC HTTP request
# after the HTTP connection is established.
rpctimeout=30

# By default, only RPC connections from localhost are allowed. Specify
# as many rpcallowip= settings as you like to allow connections from
# other hosts (and you may use * as a wildcard character):
#rpcallowip=10.1.1.*
#rpcallowip=192.168.1.*

# Listen for RPC connections on this TCP port:
rpcport=8332

# You can use bitcoind to send commands to bitcoin-qt/bitcoind
# running on another host using this option:
rpcconnect=127.0.0.1

# Use Secure Sockets Layer (also known as TLS or HTTPS) to communicate
# with Bitcoin -server or bitcoind
#rpcssl=1

# OpenSSL settings used when rpcssl=1
rpcsslciphers=TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH
rpcsslcertificatechainfile=server.cert
rpcsslprivatekeyfile=server.pem


## Network-related settings:

# Run on the test network instead of the real bitcoin network.
testnet=1

# Connect via a socks proxy
#proxy=127.0.0.1:9050

# Select the version of socks proxy to use (4-5, default: 5)
#socks=5

# Use proxy to reach tor hidden services (default: same as -proxy)
#tor=       

##############################################################
## Quick Primer on addnode vs connect ##
## Let's say for instance you use addnode=4.2.2.4 ##
## addnode will connect you to and tell you about the ##
## nodes connected to 4.2.2.4. In addition it will tell##
## the other nodes connected to it that you exist so ##
## they can connect to you. ##
## connect will not do the above when you 'connect' to it.##
## It will *only* connect you to 4.2.2.4 and no one else.##
## ##
## So if you're behind a firewall, or have other problems ##
## finding nodes, add some using 'addnode'. ##
## ##
## If you want to stay private, use 'connect' to only ##
## connect to "trusted" nodes. ##
## ##
## If you run multiple nodes on a LAN, there's no need for##
## all of them to open lots of connections. Instead ##
## 'connect' them all to one node that is port forwarded ##
## and has lots of connections. ##
## Thanks goes to [Noodle] on Freenode. ##
##############################################################

# Use as many addnode= settings as you like to attempt connection to specific peers
#addnode=69.164.218.197
#addnode=10.0.0.2:8333

# or use as many connect= settings as you like to connect ONLY to specific peers:
#connect=69.164.218.197
#connect=192.168.1.20:8333

# Do not use Internet Relay Chat to find peers.
noirc=0

# Maximum number of inbound+outbound connections.
#maxconnections=125

# Miscellaneous options

# Pre-generate this many public/private key pairs, so wallet backups will be valid
# after future transactions.
#keypool=100

# Add an optional transaction fee every time you send bitcoins.
#paytxfee=0.01

# Add timestamps to debug.log
#logtimestamps=1       


# User interface options

# Start Bitcoin minimized
#min=1

# Minimize to the system tray
minimizetotray=0

I post  a lot of options so you can play with it if you like.

The whole thing is actually working on apache httpClient:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>


To start we have too do some boilerplate coding:
//To start with a Logger is like coffee in the morning.
Logger log = LoggerFactory.getLogger(RpcServer.class.getName());
//We have to provide some cred. too login to the bitcoind
//The username and password should match the ones in the conf file.
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
        new AuthScope("127.0.0.1", 8332),
        new UsernamePasswordCredentials("user", "password"));
//Building a HttpClient for the start of the communication.
CloseableHttpClient client = HttpClients.custom()
        .setDefaultCredentialsProvider(credsProvider)
        .build();

//Setting up the request to the server. get ip and port from the
//~/.bitcoin/bitcoin.conf.

HttpPost request = new HttpPost("http://127.0.0.1:8332");

// no we start with the interesting part:
try {
    //This is the most interesting part. Here we setup the 
    //rpc call to the daemon. 
request.setEntity(new StringEntity("{\"jsonrpc\":\"1.0\" + 
,\"id\":\"curltext\",\"method\":\"getblockchaininfo\",\"params\":[]}"));
    // retrieving the response from the daemon
    HttpResponse response = client.execute(request);
    // converting the result to a string and print it.
    ByteArrayOutputStream byteArrayOutputStream = 
new ByteArrayOutputStream();
    response.getEntity().writeTo(byteArrayOutputStream);
    String theString = new String(byteArrayOutputStream.toByteArray());
    log.info(theString);
} catch (UnsupportedEncodingException e) {
    log.error("wrong url", e);
} catch (ClientProtocolException e) {
    log.error("wrong protocol", e);
} catch (IOException e) {
    log.error("io", e);
}


Conclusion

After a day of searching it was blissfully simple. 
I enjoyed talking to the legendary bitcoin daemon and 
get some information out of it. This is still a simple method.
The daemon has some more complex ones where you also might need some
parameters. At the line of request.setEntity, in the json part there
is also a parameter section. You can address all the parameters there.
Don't forget too change the method section.
For this see:
https://bitcoin.org/en/release/v0.15.0

Have fun!

zaterdag 26 augustus 2017

spring boot service with Kotlin

Introduction

Kotlin is a fairly new programming language orignally developed by jetbrains and these days supported on android by Google. Also since spring 5.0 is it possible to write kotlin programs in spring  (also spring boot applications). Kotlin runs on the jvm and is easily compatible with excisting java classes.  


The jvm it runs on at the moment I am writing this, is Java 6. No, dont worry the clever part is, that the team behind Kotlin found ways to make the features up to Java 8 available in te last version of Kotlin (1.1.4). The style of programming is more the kind of functional programming. 

Unfortunally I cannot cover Kotlin complete in this post but It will give you a rough Idea How it works and how powerfull it is. 

Lets play with some examples: 

Example 1: Hello world  


fun main(args: Array<String>) {
    println("hello world")
}

A view small points that should get our attention:

  1. There is no class definition around the main method.
  2. The declartion of the function is not void but fun
  3. the args arguments is not an String[] array but an Array type.
  4. The definition of the args is first the name : type.
  5. The println() command. In java: System.out.println().
in this small example we allready see a lot of differences which actually
lead to less code lines (lazy programmers like me love that).
The way the args types are declared, also goes for the declaration
of the var types some examples:
val double: Double = 10.0 // 64 bit
val float: Float = 10.0F // or f, 32 bit
val long: Long = 10L // 64 bit
val int: Int = 10 // 32 bit
val hexadecimal = 0x0F // Prefix '0x'
val binary = 0b01 // Prefix '0b'
Example 2 calling a java class:
// The java class
public class Test {

    public String hello() {
        return "Hello";
    }
}

// The Kotlin code:

//To declare a var you use var. To declare a constant you use val.
// Here we declare the java class defined above.
var test = Test();

fun main(args:Array<String>) {
    //Here we call the hello method declared in the Test class.
    println(test.hello());
}

Example 3: the spring boot service:

The best part of this is that the project can be an 
maven project as usual or any other build tool you desire.


The pom file needs:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>LATEST_VERSION</version>
</parent>

The code looks like follows:

//The main function comparable with what we know from Java.
//The point of interest is that the main function needs to be
//declared outside the class application. Otherwise the method
// will not be seen as a main method.
fun main(args: Array<String>) {
    SpringApplication.run(Application::class.java, *args)
}

// The class declaration simular to what we know in Java 
//with some small adjustements. By default a class is final
//in Kotlin. To undo this we need the keyword open. Spring Boot
// requires that.
@SpringBootApplication
open class Application() {
}
// finally the rest controller It has all the characteristics 
//I described earlier. Like the fun definition of the function etc.
 For the rest it is code as we know it from Spring.
@RestControllerclass CustomerController {

    @RequestMapping(value =  "/test")
    fun test(): String {
        return   "Hello world";
    }

}

To make this example work create an .kt file and
compile it with:
 kotlinc your_file.kt -include-runtime -d your_file.jar 
and run it with:
java -jar your_file.jar
Or use an ide that does this kind of work for you (leasy me again)
Conclusion:
With Kotlin we produce significant less lines of code and still have the power that we used to. Important is that Kotlin has a wide range of support from compagnies and frameworks which make our lives as programmers easier. I hope you will play a bit with it and enjoy it as much As I did. At last but not least I would like to thank Shaun Thomas from Sytac for giving a wonderfull presentation about Kotlin which enlightened me to write this post.
Have fun!

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!