 Well I'm very happy to be here and my first time in Singapore and I look forward to the following days discovering this lovely country and lovely city and so I think the Java user group is quite recent isn't it? You have had a couple of meet-ups this year, if I'm not mistaken. It's been like one year? 5 to 6 meet-ups, yeah so I'm quite happy to see so many people interested in sharing the knowledge and so as you saw on the the meet-up page well we have two presentations today and you guys let me know how fast or how slow I should go because these topics are well I get very excited with the topics that I'm going to show and when I get excited I tend to speak very very fast and so please let me know raise your hand if I should slow down by the way English is not my native language it's actually Spanish so if I sense something that you don't understand please also let me know and if you want to have a break in between also let me know if you have any questions ask me immediately don't wait until the end and I will try my best to answer them are we cool? Excellent so here we go the topic for the first one it says these Java libraries you can't afford to miss now the idea of this talk is to showcase a series of projects that or actually open source projects that you can make use on your daily work in order to make it easier faster but more important funnier a much better experience for you to do work so for that I have this particular use case now I'm pretty sure that most of you work on the server side of mobile right am I right is does anybody here actually still work with desktop applications what is Java fix or swing yeah one guy yay excellent so what I have today is an example wrap around a desktop application just because I'm a desktop guy I love the desktop but the projects I will see can be put into use in any kind of environment whether it be web or mobile or something else so because most of us have worked or still have to work with rest API this is the example I'm going to show which is how can we consume a rest API it doesn't matter how the API is written it can be done in many different ways who here is still uses or is a fan of spring boot it's probably the winning framework right now well that's one option but there are many others of course but we're going to consume this API and we want these components to be reusable we want them to be a small flexible reusable but also testable and most important of all we don't want to repeat ourselves and we want to remove all that boilerplate code because if we are working with podium base frameworks and you know the conventions of creating a java in right gators and centers and whatnot and then you can see that your code starts to grow and this is just one of the few things that if we can we should avoid so the libraries we're going to see today it's likely that you are familiar with some of them are these ones so on one side have the production libraries and the other side we have the testing libraries and here is these two alternatives you may use one or the other there's actually a way that you can use both of them together I haven't seen this too much in production but no it is possible in the case of reactive programming and you pick one depending if you are a spring fan you go with this one or you just go with the previous one in terms of login frameworks this is more popular but this one is more recent and they almost pretty much have the same feature so it's up to you to decide where do you want to go so first disclaimer all the projects that we're going to see are open source which means you can put them to work immediately and there is no string attached most of the projects are either Apache or BSD so feel free to use them as you want my goal for today is that by the end of the session you feel like this let's see if we can achieve this goal all right okay so my name is Andrew Salmaray I'm originally from Mexico that's what I say my native language is Spanish but I work for this company the Swiss company called Kenu we are kind of a small ish medium ish company where we do all the stuff that we want with Java our customers range from financial for automotive from I think we may have one of the pharmaceuticals because hey we're in Basel Switzerland where the big pharmaceuticals are so we do all the great things with Java well we also into alternative JVN languages I am pretty much into groovy have you heard about groovy before anybody here actually makes use of groovy in production besides Gradle yeah a few hands well Gradle is a great build tool and I wish I had more time to tell you all the goodness about this we'll see what I can show you today and I'm a Java champion as you can tell by that logo and this nice dish that which means I kind of like to speak about Java and promote Java based technologies and that's what I'm here I'm also a founder of the hacker gratin group where is a hacker gotten it's kind of like a hackathon but we always work in in open source projects and we don't throw away the code the goal of this the meeting is to meet new friends learn new ID shortcuts perhaps but most importantly contribute back to an open source project of your choosing so we always push back the code into a particular project so whether it be a github pull request or something else and that's it we might we have fun with pizza beer and many other things so it's a really nice way to get into open source and contribute back to community so again let me remind you the use case is this one let me show you the application as it works and I was changing to perhaps the github the third version Michael I might need the access to the network so the whole project this and didn't work okay let's try the other version that's what I can prepare and have different versions and here we go I'm gonna make it a little bit bigger there we are right so this particular application is going to connect to the github REST API and we'll query for all the repositories of our particular organization so if I enter did you notice how the load button started to became enabled and now it's disabled that's the nice things that we can do with JavaX quite easily so if I enter a valid organization this will query the network and start to populate the list here down with all the information and there is also this number here that will become important in a moment and we don't have network so that's another thing that can happen don't worry I was prepared for this let's do it again there is hotspot and let's try it again it's loading and loads repositories per page and if you can see very slightly all the repositories were sorted by name this is quite important all right so that's basically what we want to build and it's going to be built in different ways so we're gonna use the github API for one reason because it's very popular and chances are that if you are contributed to open source projects before you have encountered github in one way or another the definition of the whole API you can find it in that particular link and if we describe all the different operations that you can use for now what we're going to center only is again just query repositories how you query repositories is defining that particular URL that tells you all the different options what is the initial payload of the input for that particular URL and what will be output on the in the expected format basically what you need to do is issue a call a get call matching that particular URL pattern this will be the name of the organization in the example that I just showed this will be the value of Griffin and this will return me JSON payload with lots of information the payload looks like this it's JSON list JSON arrived with JSON objects with different properties actually the repositories have like 40 or 50 different properties for now I'm only interested in these particular ones and as you know as Java developers we like to follow certain naming conventions and when we have to use different words for a particular identifier what convention that we use we follow camel case but in the JSON world on the JavaScript world they prefer to use snake case like this there will be a mapping somehow from these properties to the other and we will see a project I will do that so in order to build this application that I just show we're going to need dependency injection I will say that in this time of our development time in 2017 building an application even a simple one like that you saw without any use of dependency injection is a little bit of a waste of time you can gain more if you start already your design thinking intense of dependency injection we definitely need an HTTP client and somehow map rest behavior on top of that we need to handle JSON mapping from JSON objects into Java we would like that way to remove all the boilerplate code that we need to write and of course we need to handle concurrency because of one interesting point for those of you that used to build desktop applications you know that there is a one rule that we should not break and that is everything that is UI related such as painting accessing properties or writing to properties must happen inside the UI thread in swing this is called the event dispatch thread and everything that is not UI related should not be in UI thread should be in any other thread whether the main thread or a background thread it doesn't matter so querying the network issuing a call to GitHub and grabbing all the repositories should happen in a background thread but once we have the results we have to display them inside the UI thread because we are changing the UI so we now have at least two different threads working and we have to handle concurrency in some way you can get the code for the application and the other variants at that particular URL everything that you see is open source as well I think that the license that I use for this code is GPL tree and Brazil it works and it's written in different ways with different libraries because as remember I showed you you could use juice for dependency injection and spring on some others so you will see the different variations how are we doing so far so good all right so let's get into dependency injection I guess most of you are familiar with dependency injection basically what we want to do is define behavior or contracts what I would recommend you if you're not doing this already I will recommend you to define your contracts using interfaces this makes it very easy to change in the implementations we like to say like just like application service that will be very trivial to migrate an application from one server to the other in terms of the dependency injection kind of trivial to move one implementation contract this to another one because it's just a matter of implementing the interface in a different way well it turns out that in this case it actually is and what you want to do is not exactly change implementations for production but mostly do it for testing because this is in testing is when you really want to tweak the behavior of one of the collaborator classes so once you define your contract in any way you want to in this case we're going to use we want to define a repository's method takes an argument and returns a collection or repository obvious we'll see in a moment what that is and we can consume this you see in JSR330 annotations JSR330 is the JSR that defines how we do dependency injection so basically it's ad-inject on the thing that we want and then we can use these things directly I'm aware that there are three ways to do dependency injection in Java the one that I prefer is to use field injection because your dependency framework mechanism will still use reflection it doesn't matter how you set it up unless you use one mechanism and one framework which is called tagger from Google this one requires compile time dependency injection this doesn't require reflection but it's not wildly used especially not on the server side so you will use some reflection so I prefer to use this way the other is to use construction injection the advantages of construction injection is that you can set these fields as final but if you have you start to have a lot of collaborators more than four or five your constructor will get bigger and the setup will be much more cumbersome especially in testing so if you have a class like this that has dependencies more than four or five construction injection might not be a good idea you may want to go back to perhaps field injection and the last option is to use setters which is the most flexible one because you can set the value at any time you want to but again now you are dealing with mutable dependencies so some people don't like this idea because they they prefer to have a stable dependencies to have them immutable okay but it's up to you to decide especially with your team which one of three options is best for you so for this for doing dependence injection I will showcase juice for the sole reason that juice is their reference implementation of jsr330 it's very easy to get started with juice what you do is you create a module it's an object type that defines how you're going to map from certain type which is called the source to another type which is called the target which is exactly what we see here there's a module and we're mapping the source type this is an interface to a target type a concrete class in a specific scope for example singleton so the dependency injection container will assert there is only one instance of this thing managed by the container here we got both the source and the target type defined the same and we're also using a singleton scope you could use prototype scope or if you're using a web application it may be session scope or application scope and here we have something that's called like a lazy initialization here's the source type is github API but we're we're binding this to a provider you can think of a provider in the spring terms the same thing as a factory beam and there are two other types of bindings we're not really used too much but just you know that everything that you do with juice has to be done programmatically the advantages again are because it's the reference implementation of jsr330 is the easiest to get started you combine any kind of types you can bind instances and you can also bind constant values those are the two other types of bindings that have been showed previously and you can provide lazy evaluated instances using providers it is extensible because the one thing if i sure well this thing is broken out one thing that i didn't show in the code is let's show the code let's edit this so it should be faster instead of opening id let's look in the code where do i need to show the life cycle yes so we go into the controller yeah we got the injections we got the view where is this post construct method it's not there no sound thank you it's not in the model so where is it it's here on the github input mpi no sorry oh i see i know i know where this thing is is in the handler i believe so yes these annotations right here post construct and pre destroy you probably say have seen this bigger of course post construct and pre destroy these annotations are very common in other environments such as cdi or web applications well juice is not aware of these annotations so if you use plain juice as it is no magic will happen you need a special extension for this to happen and locally juice is extensible so this thing will work in case that you're wondering about the extension we can see here in the build file the dependencies for this project the somewhere here is juice right there and the extension you need is this one it will give you access to the post construct and pre destroy hook points okay so as a bonus if you make use of juice you get guava as a transitive dependency guava is also a very common library that was created back in i think before jdk6 came out so it's quite mature it has a lot of information and it gives you access to new if you ever had the need to in a map to know given a value which key is related to it use a buy map if you ever had the need to have multiple values associated with a single key we not only use internally a list and we know how to handle this this idiom well the multi map does this for you already or if you want to have two keys associated to a value as if you were something like a relational table then use a new collection called table and a few other things it gives you utility classes for handling additional collections and concurrency and test and i o and it also gives you some functional capabilities who is using jdk8 already okay half of you for those of you that are still stuck somehow in jdk6 or jdk7 and you want to be able to write code in a functional way then guava is your friend once you learn how to do things with optional and predicate and function then migrate to java 8 is pretty much a no-brainer there are few changes in the api especially optional jenguava is different from the optional in jdk8 some methods names are different and a few things in behavior are different but for most of it is pretty much the same if you are not a fan of juice there you probably have encountered spring before on a spring it's a huge portfolio projects and right now i want to talk only about a spring core the initial project that created everything a spring core is more than just a dependency injection container it can give you access to jdbc to creating clients with jmx or even servers with jmx anybody here had to work with jmx all right well if you have to do it later trust me clients and servers in jmx servers with the spring it's just a couple of lines it's so easy should not be allowed another thing that i don't know if you guys know about the message format the default implementations in the jdk are not thread safe for example simple day format not thread safe also don't use java util date we got java time since java 8 so for those of you that are lucky to use java 8 switchholder already to java time forget about java util date it does not exist so message format and simple date format are not thread safe that's a bummer but there are implementations of the message format interface coming from the spring core that give you that thread safety capabilities so give it a try and so that's basically what i want to say about spring i must confess i'm a spring fanboy but i tend to use juice a lot because juice is a smaller in size and it only does one thing dependence injection nothing more so reducing boilerplate code and we're going to get into interesting waters now because the next project some people love it and the other half hate it there's no one sitting in between so we talked about java beans conventions and i know that you can tell your id to generate source code like uh you get a class define some i don't know five fields and then you say generate getters and setters and equals and hash code and that's it boom you get your class generated you know the problem with this is that this is not your code this is machine generated code but you are now responsible for handling that code because if you need to rename something yeah i can tell the id rename property good and if i need to add new property yes add a property and getters and setters a couple of clicks we're done what happens if you need to remove a property you do it by hand there is no easy way to do this right okay so that's why you guys are now in charge you have to maintain something that the machine created wouldn't be better in terms of the java beans convention that the compiler we aware of the convention if we specify somehow with certain hints i want these to be a property then generate all the appropriate code and if i anybody here familiar with the builder pattern we're going to create a new class uh that that is mutable in order to create an immutable instance so the the builder pattern has perhaps used the fluent interface design for the methods used to construct the instance so creating the builder is actually a lot of code will it be better given that this is a convention to also let the compiler build the whole thing right so for that use lumbock love it or hate it now lumbock hooks into the compiler and allows the compiler to be aware of additional non-conventions so what we're doing here with the add data annotation we're trailing the compiler that for all the fields that we have here we should have a companion setter and getter if it's not final there will be a setter if it's final it will only provide the getter and it will also generate an appropriate constructor taking all the arguments in the order that we defined them it will also generate an equals and hash code implementation that uses all of these things and it will generate that two string implementation as well and the add setter annotation i'm using it here because i'm placing a new annotation on the generated method what is that annotation json property this is for another project called jackson there are a few uh json parsing libraries in java and what a few i mean a lot they are more like 30 but jackson is perhaps the fastest one and jackson allows me to do mapping very easily but i have to do the mappings on the setter methods so with this funky annotation here we're trailing on the generated method by lumbock place this annotation i remember what i said something about this camel case a snake end convention so the incoming payload has a snake case but jackson will find that property and map it to my camel case convention and we're doing the same thing for html URL any other property that is found in the mapping remember that i said that the repository payload has like 40 properties or more if you add these on the cut on the class then all those properties are going to be ignored so now you are free to evolve your api if you want to handle just a subset of properties do this if you evolve your api and add more properties even if you had a one-to-one mapping then your code will not be broken but it will not be able to handle the new properties until you actually write new code that kind of makes sense and we also make use of the builder annotation in just a moment now be aware of the usage of the data annotation with collections in your fields especially if you're working with jpa because it's very easy to create jpa entities using lombok but if you have reference to another entity what's going to be the the default implementation of icos and hashcode by the way it's going to follow the the conventions laid out by the effective java written by josh block so we know that the icos and hashcode implementation will be sound except when you have references especially in jpa because if you have bi-directional dependencies sorry bi-directional references within the two entities the icos and hashcode of a depends on b which depends on a which depends on e infinite loop stack flow overflow the same thing happens with two strings so if you use lombok and jpa and you have reference and you have collections you have to write icos and hashcode and two strings by hand it's not a problem because add data get it and set it if it sees that you already provided that particular method if you have a custom icos and hashcode it will use it and it will not generate anything by itself so it will use your code and you should be fine here's how we can make use of the builder a static method this name could be anything you want to provide all the arguments that you want and then internally this object is the immutable one in this case i made it mutable because that's what jackson requires but in this way you could create a builder and now how do you make use of this there will be a new builder class associated with repository you call build on it and all these methods properties will have a with name or with full name that will return the same builder object and at the end you simply call dot build on it boom you get a repository object if you want to use j start 305 this is additional annotations for example non-null and nullable if you put them here say for example non-null the string name that means that when you invoke the builder you have to decode the method with name at least once if you do not and you try to build this thing it will tell you by using a runtime exception a i'm missing a name because you put right there that it should be non-null it actually on buck understands the non-null annotation from intelligent idea and it also has another annotation called not null we actually have like different four five different annotations that do the same thing for different projects on buck understands all of them to do exactly the same thing here's another thing that we can do say you have a base class called application event and another class called new instance event and this one can extend from anything you want to and you can apply add data on it so it's not a problem with hierarchies and because this is a subclass i'm telling add data to customize the equals and hash code if i do this then the generated code will check for the equals and hash code of the superclass which right now is silly because it doesn't do anything but it's an example and it also called the two string of my superclass here in the generated one because this is a final field and it has annotated with non-null the constructor will check that you have passed a value to to this property and it will regenerate the getter there will be no setter once the constructor is in buck and you pass a non-null it will throw a null pointer exception with a message saying i was expecting a value for the property instance you give give you the name but it was known so it's better than just simply say null pointer exception on line 41 or something so it's quite good now long book allows you to again reduce the boilerplate code by generated bytecode instead of generated source code so if you need to change something you need to have new getters and setters what do you do you go back to your pojo add a new property perhaps customize some uh once with additional annotations and recompile and boom you get all the code already and then you may be thinking what about the idea if this works at compile time i need to work at source time my consumers must be aware of the different methods that are going to be created isn't it well if you're using netbins uh lombok understands netbins understands all the additions by lombok by the default if you're using intelligent there's an additional plugin very easy to install that will give intelligent all the hints about the different methods that are going to be added and if you're using eclipse uh lombok is a little bit more difficult to configure just because a lombok requires the apt tool the annotation processor tool which is a pain to configure an eclipse but lombok comes in with a very trivial ui that allows you to configure lombok very easily just double click on it set it up point it to your id you're done in business nothing has to be done uh so don't forget to enable annotation processor in your project in your id again in netbins there's nothing to do an intelligent is one check per project and in eclipse you have to do it explicitly if you give a try to lombok i will recommend you to use only add data get there set there and build there there are a few other annotations right there uh provided by lombok but they fall into either the experimental case or the really scary case because what lombok does is rewrite the biker don't be afraid still safe to use we use it with our customers we and our customer half of there are banks and they are fine with this and it works and there's no data and no money lost so it works how are we doing so far okay questions no good you gave me let me know okay now let's turn into behavior and while we are working with an application we would like to know what things are happening how how is the data flowing from one place to another what is the first thing that we do as developers to figure out what's going on with our application system dot out print line right uh yes fine but it would be better we be able to be to have this information in a more persistent way right for example a log so we can use different login frameworks i'm going to put it right now out there there is no good login framework in java none there are many out of there none of them are good but for all of them the least worse is this one sla4j because that itself 4j has two features that i really like one is that it doesn't matter if you're using java commons login sorry java youtube login or apache commons login or log4j which version one or lock back or a few others all of these different frameworks can or the calls of these different frameworks can be routed to a single endpoint and this is the sla4j why would you like to do that or why would you do this because when you have a big project and you're consuming different dependencies chances are that none of these dependencies had agreed upon on which login framework to use so you may have a collection of all different ones right but you want to centralize in just one place how to configure login so this is exactly what sla4j allows you it puts everything in one basket so now you only need to configure login in one place the next thing that we do in login is when we do a login statement for example lock.info and we pass on string if it's a plain string nothing is wrong if we construct a string based on a pen on a few other objects it may be a little bit expensive to create the final message and once this is done it gets passed to the to the login method in this case info and guess what if the info level is not enabled what happens with that object that we just created goes away discarded but we lost cycles creating this thing so that's why we as developers what do we do we guard our login statements we do if lock level such level info is enabled then we do lock info right whatever code starts to look a lot a lot uglier because if here and if there and whatnot but if we use a variable arguments method then you invoke the method lock info then give it a string that can work like a like a formatted message like you remember the old days printf and scanf from c and as additional elements the actual values that are going to be set on the final message so internally this method will do the check for you check is the level that you're invoking is enabled if it is constructs the message and sends it that is much better so both slf4j and lock4j2 have these features okay next one let's do HTTP there are many ways to do HTTP with java actually java comes in with a very basic HTTP client it's called URL connection but it's very low level so there are other projects out there allows you to create HTTP clients most likely you have encountered Apache HTTP clients from the HTTP components which is I would say kind of okay but how many of you have had the need already to consume services provided by the HTTP tool not yet but you will at the moment that you do let me tell you that none of the options that you probably have seen so far support HTTP 2 except this guy this project called okay HTTP it's a very basic HTTP client a small memory footprint because it also works on android and is HTTP 2 ready since like two years ago here's how you do it you create a client then define you can this method this is just a single method you create a request and you can pass as many headers as you want in this case I'm not sending any headers define the URL what's the body of that object you build this thing here's my request send it to the client you get a response back on the response you can query for the headers for the status measures the status code everything that that gives access to what is the underlying HTTP mechanism and if everything is fine look what this thing is doing response that body here's graphs the body dot string now the body that we're receiving or that we're expecting is JSON isn't it we need somehow a way to map JSON content into java objects and that's what is going to come next the advantage is again of kctp is that is HTTP 2 client ready the behavior and the configuration extensible via factories this is going to seem just a moment and you can intercept the lifecycle of HTTP so if you want to listen our spoof for tokens or authentication or something else register an interceptor on your client is very easy not that i was suggested to do bad things with those headers but anyway uh now okay we can do HTTP no problem but we are java developers do we need to work really with just json and javascript my low level thongs no we want to work with java objects would it be a way to map automatically json to java and vice versa so that when we say i want to have a list of objects java objects i just get the objects instead of doing the mapping myself how many ways out there to implement rest rest is very easy get post delete head there's no a different behavior how we do get post delete head and put right so for that i'll suggest to have a look at this protocol retrofit now retrofit is quite cool as a developer what you need to do is the following we define the contract of our api if you look back into the if you were to look into the link that provided earlier there are two ways that we can query for the repositories we start by setting the name of the repository and this will give me a set of results but if the results are paginated then in the headers i will get additional links and instruction on how to follow those links so when you saw the application running had like 245 repositories and the number advanced by increments of 30 is because github paginates element by 30 i could change that of course so what was happening is that for the first page this method was in bulk and for the next pages once the header were inspected if there was a link it will follow using this other method regardless of that what is the return value a list of repository objects wrap around in an object of type call this is from retrofit what call will give me access is to their response so i can query if it's successful or not i can also query this thing for its headers to figure out if i had to follow a new link or not all right so just a simple interface what's the next step create the actual http client like this there's a builder i can set up some basic configuration for example what is the url i want to use the standard url from github here's a factory the jackson converter factory so now the reprofit client will be able to do the conversion for me using jackson and then so i build that object and then notice this object the builder create given the interface that we defined before the return for this is actually a java lang reflux proxy that uses this api but internally uses the http builder created here so in the end as a developer the only thing that you need to do as a consumer of the api is this this is the object call the method this just looks like a java method isn't it like any other java object that you do and what would be the response of this it will be a list of repositories already mapped from jason there's nothing else that you need to do it's as simple as this another advantage of using retrofit is that it relies on htp already so it's a small memory footprint it's quite easy to get started the apis of both retrofit and htp are quite simple similar they follow the building pattern so if you know how to use one it will be very quite easy you're going to find how to use the second api are we doing okay because that was part of the magic the next one multi-treaded code how do we deal with doing the right thing in a desktop application remember everything that is ui happens in one thread everything that is not happens in a different thread uh that means that we have to issue the network call in a different thread handle it and then push back all the results into a different thread is there something else is there something in the past that you have seen that works like this the guys that did swing development jdk6 swing worker it allows to issue a task to run it in a background thread and then come back at any time right but in the javascript world we have something else it's called premises wouldn't be cool if we had promises in java okay for those of you that say java eight you have something that looks like a promise but it's kind of broken and i will tell you why this class is called completable future it's broken because it's what a promise that is supposed to be fully async non-blocking and it's also a future which is blocking so what is it is it a fruit a future or is a promise if it's non-blocking it or it's blocking it's both and it shouldn't so if you use it as a future fine if you use it as a promise fine but if there is a another place of your code that takes a completable future and then use it as a future because it extends from future then it becomes blocking and that's a problem so just be aware of the different uses of completable future and because some of you also said we are not able to use jdk8 for now no worries you can use jdfair which is a project that runs in jdk6 and it also runs on android and it gives you that behavior promises so what a promise is is basically the idea of the scheduling a task in the background and then you register callbacks on that when this thing is done i will do this if this thing fails i will do that when this thing finishes regardless of if it's correctly or fails then i will do something else right this is the idea inspired by j query promises so what we want to do now what we're going to do now is modify our api to take a promise and this first generic value is the return type i respect it will be a collection of repository objects the project that we saw before now at any point in time during the execution of the background test there may be errors and we want to notify these errors errors could be exceptions or troubles that will be this type but jdfair allows you to throw any kind of object it could be a string it could be another collection it could be anything that is uh that the application requires and the last thing remember what i said something about swim worker swim worker while you were working in the background it will allow you to push intermediate results back to the UI so this will be like like a progress well that is the third element if you need to notify the consumer the person or the component that register callbacks of intermediate results how the the progress of the task is then you can use that okay so let me show you how you schedule the background task and then how you're going to consume it for this again using the dependence injection we know this now there's a new type here coming from jdfair it's a deferred manager this is the component that allows you to bootstrap or to issue a task in any kind of executor you can actually define which executor service you need to use for the deferred manager right so now we're going to create a promise so with deferred manager when and look at that a lambda expression but you can also use anonymous classes if you want in jdk6 and jdk7 so this is actually the task that we need to invoke let's see at that api what is that it's our retrofit enable client remember and we're calling it just like a regular java call so we call this execute and we get what our response of objects perfect now what do we do we ask you the responsive successful if it is just rest on the body and by doing this the mapping from jason to java will happen and what do we get a collection of repositories already there's nothing else to do and if not successful then we throw an exception with any message that we want or anything that we want exactly and that's it no this is just three lines of code and this is all that we need to issue a call to github just one page come back and parse all the results isn't that great that's a time seven how do we consume this the trick is in this type the promise there is another component in the application called a controller i like to uh to use the mbc pattern when creating desktop applications so the controller is the one that says i'm going to consume the promise so let's see github is the object that returns the promise so this is the promise that right there in this particular version i will handle intermediate results all right and then we're going to register callbacks on the promise if there any intermediate results what i'm going to do is what is that a method reference in java 8 so we're going to add the element directly to a list all right if it fails right now i'm just going to print out to the stack trace to the system error and regardless if it fails or if it's successful we're going to set some state remember when it started to type on the application and the the bottom the blue one became enabled but the moment that i hit on it the cancel button the red one become enabled that is because we're changing the state and that is because of that and when i set the state to ready the the cancel button becomes disabled now this is great because if you know promises from other environments then you can apply it directly right away with java it works with jk6 you can change promises from one to another you can even adapt values from one another and you can use land expressions but promises as they are currently implemented are a one shot execution you simply say do this and when it's finished or fails do that what if you wanted or you needed to consume the values as a series of events in a streamable fashion perhaps are there alternatives yeah we jump into reactive programming and reacting programming is nothing new for those of you that's the swing you know this already this is just basic property chain listener and property chain event that's all that we're doing with different names and a lot of operations rx java is one of the initial projects that started with the reactive programming in java so it's probably the most known project out there so what we're going to do is a thing instead of creating a promise we're going to use an observable this is rx java 1 in rx java 2 you will probably go with flowable why is the difference flowable in rx java 2 is a stream of values that also support a concept called back pressure and what is back pressure if the server is too fast in producing content and the client is too slow to consume the content then the client is going to be bogged down so what the client says using back pressure to the server is please stop or slow them or wait up so that i can finish this task that i could be doing and when i'm done i'm going to consume everything else and you can take this thing around in rx java 1 observable kind of had back pressure but it wasn't the right thing to do in rx java 2 they decide to split the behavior and if you need back pressure it is flowable and if it's just a series of events without back pressure it's observable it's as simple as that so now we got an observable all right and then what we do is decorate the observable with different operations we take we're going to say well the event might produce like a thousand events this stream but we only want to take as much as that particular value perhaps 10 perhaps 100 and i said something we are decorating the observable because this observable is not exactly the same observable returned by this right so i can start refer to this and do something else but with this this operation will be different and now we continue to do the same thing and we continue to change so we actually have different observables until we we reach the end so what are we saying here we're going to have a timeout that's important because if the network call takes too long then we don't want to wait forever so let's limit a timeout of 10 seconds then when we subscribe that means when we are starting the connection we're going to change the state again the button and if it terminates regardless if i'm successful or an error we're going to change the state again nice we're going to subscribe on a background thread otherwise it will be the same thread as the color we don't want to do that and when we subscribe there are many ways to handle this but for each element or this each event that's coming down the stream we're going to add it to a list and if there's any errors we're going to print it out this is very similar to what we saw before with the promise how we handle this but the arrangement is different so now you may be thinking this is nice but that is just plain xjava where is our htp client is there a way that we can combine xjava and retrofit because what yeah you can what are the changes from this side they look exactly the same parameters what changes is the return type this used to be just called now it's observable of response of the type of objects that we want the next step is to configure the the retrofit builder to let him be aware that you also want to use xjava just one line of code register a new factory and that's it nothing more so now you can issue a call get an observable and inspect the response and do anything that you need and given that we want to consume different pages we had to find a way to combine all these different lists because every time that we query for a page what are we going to get a list of repository and then we follow the next page another list and another list but we need to have something that is just one set of events one set of repositories we need an observable so for this we need to concatenate and flat map all the list into just a single structure so here's one way that we can do it this again this is just custom code for the application consuming our xjava when we call this method we're gonna have we have two lambda expressions one for the first method called remember that takes the organization name and another that inspects the links object this is how we will pass the headers and follows using the next URL so the different method called right and that's it how do we do the concatenation it's thanks to the operation that our xjava exposes just like this we call the first page and there is a next one it will call this method and what is this method this one returns the observable of titi which is repository not least a repository because again we're flat mapping so flat map right there one of the operations that we can call on the operator on the observable and for each response what we're going to do finding it has headers finding there is a link header in that thing grab other responses right there and if it has links then follow it concatenating at the end again all those different lists get pushed into just a single stream of repository objects so your consumer becomes very easy as we saw before it's just a repository as it keeps streaming out from the source there are more operations that you can call on unobservables and just be aware that every operation that you invoke will generate a new observable i like to showcase our xjava because it's the initial one but if you are keen to using the spring-based projects then there is project reactor the api between xjava and project reactor are very similar in xjava they call it flowable in reactor they call it flux there is a single stream in xjava a single element stream that is called single in reactor is called mono that's it finally this is the last thing that we do for production and then we get into testing is the component communication so when i tried to use the application for the first time you saw that a dialogue pop-up saying i didn't i i don't have network well so far what i have done in the shown in the code is that it will encounter a problem accessing the client we print out to the stack trace right to the to the to the console but it will be better to showcase a dialogue or do something else but the controller should not be aware of what's going on you simply say something like hey i encountered an error so now i'm going to ship that error somewhere else and somebody should be able to handle it how do we do this well we can use an event bus and even though wava provides a simple event bus it's not as highly configurable and flexible as this one it's called ambassador here is how we publish an event you will have to create your own custom event is a subclass of a very basic event boss class provided by ambassador and you can use injection of course if you want to and then the only thing that changes is this line of code instead of printing we instruct the event boss to publish a new event remember this class that we saw earlier with lombok here's the example by passing it directly to the constructor the instance object and we publish in two ways we can simply say publish which is synchronous that means the producer this component will wait for all the listeners all the consumers to be done with the event that may be sometimes what you need in our case we simply say publish asynchronous which is fire and forget here's the event and the producer continues to do this thing and the consumers will do whatever they need to do at another point in time in a different thread and that's it how do we consume this thing like this we have again the reference to the event boss and we have to register ourselves with the event boss as a consumer nice usage of post-construct that pretty pretty story because once this property has been injected this dependency has been resolved this method will be called immediately and then we'll register ourselves and when the dependency injection container says this instant is gone we don't need it we unregister ourselves always be good citizens i'm really keen on using symmetric apis if there is something to say i'll register myself i will expect that api to allow me to unregister myself so that i can use this nice lifecycle handling mechanism so that i can do the right thing at the proper time the last thing to do is this the handler the important thing is the annotation and the event type the name of the method not important so when we register ourselves with the event boss it will have it will look at all the different methods that we have annotated and match the arguments so when someone ships or sets or publishes an event of that type this method is going to be handled it's going to be in bulk and that's it you can filter if these events by subtype you want to or by other means but this is the very basic concept now i like that ambassador is quite fast is quite good and there is a link to performance within other alternatives but be aware that the author of the project is no longer as active as it was before so if you encounter a problem if you encounter a bug the reply and or the the fix will not be or not happen as soon as you may expect that's how open source work this being said we have this in production and we have this with banks and it works pretty good we haven't found any problems that we cannot fix so far so it's still good how we doing good you guys let me know if you need a rest because now that we have finished production code we get into the interesting bit of testing because we all do testing right yay no perhaps if we have time that's kind of the problem if we have time but let me tell you that the price that we're going to see we allow you to have that extra time because we'll reduce the amount of code that you need to write in order to do testing so let's see some hands uh who uses j unit four for testing okay like 30 uh testing g there's always one person nice uh spark uh-huh here's an opportunity good so for those that use j unit four uh have you ever had the need to parameterize a test case all right so here's how you do parameterizing of test cases you define a method that takes some arguments say for example three arguments and there's a string a string integrand you parameterize it using the annotations you're done perfect now you have the same setup and you need a different set of parameterization now you need int string map can you do this no here's another method i just need a map can you do this no not in the same test case you have to write a different test case that's kind of bad because these three methods belong to the same testing unit if you will but in order to be able to do this you can use a project called j unit ramps it's an extension of j unit that requires a custom runner it's right there with this you can parameterize as many methods in the same test case with different arguments and with different types of arguments and there are three ways for you to parameterize one you define the values right there in the method like this this is an empty string not double quotes but not actually no this is not the this is just hold on a second uh this is weird no yeah here's the empty string right there and so we have two values there and two values there given the input blank we spec that value given the input test we expect that value you can also define the name of a method that functions as a data provider or you can also define a class that has a simple simple method that returns the values notice the other thing the method names the method now takes arguments or the right type with the right name so there will be some data transformation if this thing were to expect integers or some other type so given that we create our instance our class under test in this case is the service then we expect this thing that we call that with that input and we spec that that output I guess most of you are familiar with this this is ham crest and j unit four okay we'll see in the the following up presentation what we can do better to do what we can do better to do here with messages but this is very simple again the single constraint that you have when using unit programs you need a custom runner if you're already using a runner for other means then you cannot use j unit programs with the same test case that would be a problem okay the next one is when we have a class under test and we have different collaborators we need to set up some kind of fake collaborators don't we because we only want to test the class on the test that's the whole point what do we do in this case do we create new instances on the on the fly like anonymous in the classes or define a custom class in the test case or something that is shared by other test cases well I would say that it's better if we use something like a mocking framework and of all the different mocking frameworks moquito is the one that is leading the pack and here's how you can tell you can think of moquito as a DSL for defining expectations all of the entry points of moquito are done via static methods so let's see using j unit programs which is independent of moquito by the way here's a class under test is the controller the model is a plain pojo so we use it as is and then we do set service of and here's the entry point we mock that interface again the reason why I would prefer to use define back define contracts by interfaces is that makes them testing much much easier all right here we go then we define the expectations when that mock which is the one that we set there we invoke the method with such input then we expect some output so far so good we invoke the stimuli here the controller we internally invoke the service right and then we verify that the controller did the right thing we're also verified that the mock that mock was in bulk once with such method and that input if this is okay but this is not then there is a problem the controller is lying to us it found the appropriate result but with a different mechanism that was not following in our expectations that's what we have this thing here so with moquito you can have three type of objects you can have stops which are like this one when you simply say given this input return that output I don't care what it is there are mocks which given this input you return that output but you must call that method in certain order and with certain cardinality if either of these two are wrong even if you verify this it will tell you there is a problem because mocks are very strict and finally we got spies the spies are real objects for which would you want to invoke some of the real behavior some of the production what's going on production code but some of the methods you need to fake them out for the purpose of the particular test case that you're running the spies are not so much used in the wild but there can be they can become useful because sometimes you don't want to mock a lot of things you know for something to happen it's better to use the real deal with just a small tweak think of testing exceptions if someone is obsessed with having a hundred percent coverage it's very likely to happen if you do not test all the branches especially with exceptions and if there is a very specific case that you cannot reproduce then using a real spy with a mock you can throw a specific exception on a particular code pad and boom you get a hundred percent code coverage back again moquito is pretty much a fluid dsl based on static methods it provides again stops mocks and spies it can mock interfaces abstract classes concrete classes and final classes it's kind of weird it works and i don't recommend you to do this it's mostly because you may be dealing with legacy code that for some reason decided to define a final class that needs to be tested and is a collaborator you can still do this with moquito okay so some of you use j unit so you might use juice and you may be thinking oh i want to use moquito so bring three projects together hmm what about juquito juquito is pretty much these things three together combine yeah sounds weird it's created by by a french company and they say juquito sounds like martial arts yeah okay so this thing also has a custom runner uh you run with j unit four uh it allows you to do dependence injection on the test case look at that and for any type for which you do not provide a binding guess what a mock will be created automatically for you this is great because if you have kind of like an integration test case where you need to have the same mock used by two different classes if you were to do this by hand let me tell you it's going to be troublesome to inject that single mock in two different places but juquito does that for you and here's for example here's a method i don't tell you with j unit at before when we pass an argument for which there is no binding so this is a mock so this is the same kind of expectation that we had before right with concrete values and now the test case looks pretty much the same as before here's the model uh we set some values on it execute the stimuli and then the assertions uh wait a second we didn't have to inject the service in the controller as we did before we didn't have to do it explicitly why because the controller is injected by the dependency injection container and the mock is also available in the container so when we are we invoke the controller right here this thing has all its dependencies their real ones the mock ones stop and spice everything is ready here so the only thing that we need to do is run it verify and verify the mock or stop as well much much easier um so it brings together the three projects the unit juice and moquito under one roof and uh there is another way there's another notation that you could use here i think that is called at all so you have multiple bindings of the same value you can parameterize this test case so say that you have had three different bindings then i have three different invocations on the same test case why because given that we're using a custom runner we cannot parameterize this test case using j unit prance because it requires another custom runner so that's an advantage okay so have you said that you have used groovy in the past but none of you said that you're using a spark so if you're feeling adventures i highly recommend you to have a look at this a spark is a groovy dsl for creating tests so all the behavior that we saw before parameterization and mocking and a plus a few other features are brought by just a spark and a spark is j unit compatible so if you have a specific j unit extension that you want to run or use then you can use it with a spark so let's see what's going on here first we have to write groovy code but uh groovy code is very easy or very similar to java uh you had geyonla for a few months ago i think that he he gave a talk on groovy so here's how you do things with groovy you currently have your java code right stick it as it is rename the file to dot groovy pass it to the groovy compiler 98 percent of times the code is going to work and compile because groovy is pretty much a super set of the java syntax there are a few changes especially in java 8 we are still not ready 100 compatible but if you still in jdk7 then it's going to work so you came here looking for java libraries you cannot afford to miss and a few other projects and testing but you will leave this talk knowing another programming language you can use groovy right away just rename your files it's as easy as that then we remove a lot of noise for example no semicolons uh property access now a few other things now let's see what is this this is the uh placeholder or the dynamic type definition this is the same thing as object in a spot you can use void or def it doesn't matter but what is that is that a method name uh maybe because it has the parentheses embraced but what is that it's a string isn't it weird and it has the spaces and this character what's going on here well let me tell you that java the jbm language sorry the the jbm allows you to use any kind of characters as an identifier just like spaces but it's java the language the one that says no i'm going to restrict the set of characters to just this which excludes spaces and this character how do you call this character octosharp hash right has different names anyway so what's going on here is that this test method is already parameterized and these are placeholders for the values and because this is a string then i can be as expressive as i want if i really want to then because groovy has multi-line string support i can write a whole paragraph right there i can be very creative with the content not just following test camel case convention with something that looks quite weird and that's not really parameterizable all right now you saw before in the other test cases that i was using comments for these blocks given when then something like this and i was just getting you ready for a spark because these blocks have a special meaning to you as a regular java developer they may look just like regular labels or code blocks right but for a spark this means in this block i'm going to initialize some values this is how i'm going to set up my test case given and set up our aliases the next one is a stimuli block this is where we expect the real deal to happen and then come the assertions i said assertions but what is that a value using property access controller get model get output that's actually what the compiler will see getters this is not field access and this is probably a string that is a string what is that an equals operator is that how we compare strings no but we wish we could right well groovy has operator overloading so this operator actually invokes the equals method for us so it does the right thing perfect so these equals that where is the assertion it is an implicit assertion because it happens inside the dem block it is assumed by a spark that all the operations that are following this block can be able later into a Boolean context using what is known as the groovy truth which means if this evaluates to a Boolean truth perfect if this evaluates to a collection and if it's empty it's going to be false if this is a pattern matching operation and returns no matches it's going to be false if there is at least one match it's going to be truth and we follow how the rules of the groovy truth that makes our assertions much more concise and the last thing that we see here is one of the ways that we can parameterize our test case output and input those things are defined in here this operator is the left shift operator is pretty much calling add on something these somethings and these is a collection literal that we wish we had collection literals in java coming up in java nine using factory methods list of math of set off direct syntax so this is a list with two strings and here's another list with two strings so the first value of input will be empty and the first value of output will be how do you strange second value second value execute done the final thing that i didn't show is that that's how we create a mock pass the value and then using a closure or a bland expression if you will we specify that in this method with that value then will generate certain output and we can add as many as we want which we're going to invoke in that order and because we define just once this is just one invocation so we invoke this this this this mock more than once and we had a special verification it will let us know that it will fail so it's basically a groovy dsl for doing testing is junit friendly you can parameterize you can mock you can do all the crazy and magical things that groovy allows you to do i have seen many teams following the standard java conventions for the production code but choosing a spark instead of junit for the testing purposes we're almost done with this we know that we're dealing with concurrency right and how do we usually test concurrent code so for example we know that something has to be run on the background and we have to wait for that process to finish so we can continue what's the natural thing to do we use a thread-to-slip right and then we simply say looks like two seconds is fine what if the operation takes more than that fails or if it takes less than that well i still waited two seconds because that's the limit right would it be better if there were a conditional weight the conditional weight that we can wait right as much as but no more so that's precisely what our utility allows us to do with our utility and we know for a fact that the controller is going to run on a background thread and so we do the setup as we know okay perfect this time is using observables that's fine all right so we know this thing will run on the background perfect we load so this invokes the observable in the background and then here's the entry point we are wait up to two seconds but it could be less for this condition we're using a method reference but it could be a lambda to be equal to some value using hand crest matchers so once with this happens if it's before two seconds the test case will continue if we take two seconds or more the test case fails it's too slow and if it continues when you do the right verification assertions and whatnot with if we had any mocks like that and that's it so the advantage of i-waitility is that it has a conditional weight instruction it's pretty much a dsl again it has extensions for java 8 so that i can use lambdas for groovy so you can use closures and for scala if you want to use functions scala functions and all the conditions are customizable using hand crest matchers finally and here i'm going to run the test for real and i'm going to disable network so not cheating and let's do the tests and one of this case is a functional test case that will fake out the github api somehow because again no network because it will be kind of silly look no hands it will be kind of silly that our test case will hit the real github server every time isn't it it will also be difficult for us to have a external server on which we have the right setup for a particular test case before we run the test case what if there are concurrent test cases trying to access the same server that's kind of a problem it better if we can pull in that server into the test case we know that if you use maven or gradle you can bootstrap a server as part of the test but it used to have the problem of a perhaps a shared test server within different test cases it will be better if we are able to have a single fake server per test case and that is exactly what wiremark allows us to do a wiremark can be run using a junit rule if you haven't seen rules there are pretty much like test case decorators apply behavior before and after a test method or before and after a whole test case the way that have set up wiremark if you see in the code is a simple test rule so a method rule so before and after the test method so once we have the fake server running we're going to stop for a particular get URL and if that get URL matches then we're going to reply with a status response of 200 so everything is good with some headers perfect and some content matched up as json this is actually making use of jackson again to marshal from java to json in this case and if we found this other URL then we responded something there actually the code if we see it I think there is an example where let me be go this way there is an example where the test case we make an error let's see it in this this functional test case here so there's the the rule right there this is the the fake server listening on import 8080 and then here's the happy path we always test the happy path where we match that particular URL and is that the case then just reply this is exactly the same as the as in these slides then we click this is using another product called test effects it's only usable for java effects uis this is the one that saw display in the ui and what happens if we cancel we can reply with fixed delay so we're going to wait 200 milliseconds and we reply with this and say something else well you can also I don't know if we have the error path here yeah failure path we reply with a status 500 and such error and then we verify that the the dialogue that says the alert what was shown in this case so now we have a fully functional functional test case that is completely independent from the real server and we can play around with all the settings required in order for this test case to work how about that okay this pretty much finishes this part of the presentation and we can follow up with test cases so before i finish this i would like to show you this i have started a newsletter when i on which i talk about these things and i think that i'm about issue number three is about to be published and the second link is the same newsletter but in spanish so if you got any spanish-speaking friends please let them know about the second link as well and i will i like to discuss all the topics that we saw today and a few others on this short blog post and presentation so please subscribe and if you have any questions please let me know if you want to take a break then we take a break or should we continue with the next presentation given that half of the present the next presentation we have already seen it would be quite fast like 30 minutes or so so what do you guys want to do take a break all right so 10 minutes and we resume at 10 at 9 all right perfect works for me