Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

and many more ....

Featured FREE Whitepapers

What's New Here?


Gradle Goodness: Using and Working with Gradle Version

To get the current Gradle version we can use the gradleVersion property of the Gradle object. This returns a string value we can use for displaying the values. If we want to compare Gradle versions we can use the GradleVersion object. With this class we can get the current version, but we can also compare Gradle versions. This can be useful in our build scripts if we have functionality based on a Gradle version. In the following build file we first have a task that uses the gradleVersion of Gradle. Then inside the task we use the static method current of the GradleVersion class. We get an GradleVersion instance and we display different properties from this instance. In the task compareGradleVersion we create a GradleVersion instance with the static version method. We compare multiple GradleVersion objects and have different functionality based on the Gradle version. task printGradleVersion ...

What is Product Management?

Summary Product management is a multi-faceted, complex discipline that can be difficult to grasp and hard to master. This post shares my take on what product management is and what it takes to work as an effective product manager and product owner. It presents a product management framework that helps you define specific product roles and identify gaps in your product knowledge.         I often get asked what it takes to be an effective product manager or product owner, which product skills the individuals should have, and how a company can strengthen its product management function. Answering these questions requires an understanding of what effective product management looks like in the digital age. The following picture shows how I view product management: It depicts a product management framework that consists of six core knowledge areas and by six supporting ones. The core areas are orange and placed centrally. The supporting ones are purple and located at the edge of the circle. You can download the picture for free by simply clicking on it or from core areas are particularly important for doing a great job as a product manager or product owner. You should hence strive to become knowledgeable in all of them. The supporting areas are also important for your work, especially when you manage commercial products, but generally not as crucial. If the product management framework with its knowledge areas feels overwhelming then don’t worry: Product management is a complex and demanding discipline that is not easy to master. It takes time and effort to become a competent product manager or product owner. The good news is that you can use the framework to spot gaps in your skill set so you can address them. The Core Knowledge Areas Vision and Leadership: Working as an effective product managers or product owner requires vision and leadership skills. You should be able to establish a shared vision, set realistic goals, and describe the benefits your product should deliver. You should be able to actively listen to others and negotiate to reach agreement and get buy-in. At the same time, you should not shy away from making the right product decisions even if they are tough and do not please everyone. You should be able to manage the stakeholders including customers and users, senior management, development, marketing, sales, support, and other business groups that have to contribute to the product success. You should be able to effectively communicate with and influence them. You be comfortable working with a broad range of people from diverse backgrounds including a cross-functional development team. Product Lifecycle Management: Managing a product successfully involves more than getting it built and released. You should understand the product lifecycle with its stages and the key events in the life of your product including launch, product-market fit, and end of sales; you should know how the lifecycle helps you maximise the benefits your product creates across its entire life; this includes the lifecycle’s impact on the product performance (revenue and profits), the product goals, the pricing and the marketing strategy; the options to revive growth as your product matures and growth starts to stagnate. Product Strategy and Market Research: Your product exists to serve a market or market segment, a group of people whose need the product addresses. You therefore should be able to identify your target users and customers and segment the market; you should be able to clearly state the value proposition of your product, why people would want to use and buy it and why your product does a great job at creating value for them. You should be able to carry out a competitor analysis to understand their respective strengths and weaknesses; you should be able to position your product, and determine the values the brand needs to communicate. You should be able to perform the necessary market research work to test your ideas and assumptions about the market segment and the value proposition. This includes qualitative and quantitative methods including problem interviews, direct observations, and employing minimum viable products (MVPs); you should be able to leverage data to make the right decisions. This includes using an analytics tool, analysing the data effectively, and deciding if you should pivot and change your strategy or if you should persevere and refine it. Business Model and Financials: To provide an investment incentive for your company and to make developing and providing the product sustainable, you have to be able to determine the value the product creates for your firm. You should be able to formulate and prioritise business goals, for instance, enter a new market, meet a revenue or profit goal, save cost, or develop the brand. You should be able to describe how your product’s value proposition is monetised and capture how the business model works including the revenue sources and the main cost factors. You should also be able to create a financial forecast or business case that describes when a break-even is likely to occur and when your product may become profitable. In practice, you may want to partner with a colleague from the finance department to carry out this work. Product Roadmap: Many people have to contribute to the success of a digital product. To help them do their work and to provide visibility of how your product is likely to evolve, you should be able to create and use a product roadmap. This includes formulating realistic product goals (benefits), metrics and key performance indicators (KPIs), release dates or timeframes, and key features (deliverables or results). You should be clear on the relationship between the product strategy and the product roadmap. You should be able to formulate a go-to-market strategy and capture it in your roadmap. You should understand when the roadmap should be reviewed and changed. User Experience and Product Backlog: A great product has to offer a great user experience (UX). You should be able to describe the desired user experience. This includes describing users and customer as personas, capturing the user interaction, the visual design, the functional and the non-functional aspects of your product together with the help of the cross-functional team (a UX/UI expert should be part of the team). You should be able to create scenarios, epics, user stories, storyboards, workflow diagrams and storymaps, and be able to work with user interface sketches and mock-ups. You should be able to stock and manage the product backlog, prioritise it effectively, and select sprint goals. You should know how to understand if you develop a product with the right features and the right UX, how to test the appropriate aspects of your product and how to collect the relevant feedback and data. This includes the ability to perform product demoes, solution interviews, usability tests, A/B tests, and direct observation. You should be able to use an analytics tool to retrieve the relevant data and be able to analyse it effectively. You be able to change (or “groom”) the product backlog using the newly gained insights. The Supporting Knowledge Areas General Market Knowledge: Understand who your current customers and users are, what product you offer them today including their value proposition and business model, what competitors you have, how big your market share currently is, and which market segments you serve well. Development/Technologies: Be a competent partner for development/IT/engineering, have an interest in software technologies, be comfortable collaborating with a cross-functional technical team. Marketing: Be a respected partner for (product) marketing; be able to help select the right select the right marketing channels and to determine the right marketing mix; help marketing with creating the marketing collateral. Sales and Support: Be a respected partner for sales and support; be able to help select the right sales channels and create the sales collateral and training. Project/Release management: Be able to determine the primary success factor for a major release/product version and to steer the development project; be able to determine the project progress to forecast the progress, for instance, using a release burndown chart; be able to work with the Definition of Done; be able to trade-off scope, time, and budget. Process: Have a good understanding of ideation and innovation processes to generate and select ideas and to bring new products and new features to life. These should include Customer Development/Lean Startup, Business Model Generation, Scrum, and Kanban. Defining Product Roles with the Framework My product management framework helps you define product roles and the skills and responsibilities they should have. Using the framework, I can, for instance, define the role of a product owner in the following way:As the picture above shows, a product owner should have strategic product management skills such as product strategy and roadmapping as well as tactical ones (UX and product backlog). I have circled the areas, which are required by Scrum – the framework in which the role originated – in dark orange. The other areas are necessary to allow the product owner to do a great job and achieve product success even though they are not mandated by Scrum. You may, of course, disagree with my take on the product owner role and may want to use the framework to capture your definition of the role. Another example of how you can apply the framework is the description of the role of a tech product manager, a product manager who looks after a technical product and requires more in-depth technology/development skills, as the following picture illustrates.For instance, one of my clients is a major games development company, which has its own in-house developed physics engine, a complex piece of software that does all the clever animation. The product owner of the physics engine is a former developer. This makes sense, as the individual requires a detailed technical knowledge about the product and has to be able to communicate effectively with the users, the game developers. If you work as a product manager who looks after digital products that are developed and used in-house, for instance, a finance or HR application, then you probably have to tailor the supporting areas as the following picture shows:In the picture above, I have removed “Marketing” and  replaced “Sales and Support” with “Operations”. I have kept “General Market Knowledge” as it is desirable for the product manager of a finance application to understand the market, that is, how the finance group works, what problems people struggle with, which products they use, and so forth. Determining Learning Measures with the Framework You can also use the product management framework to identify gaps in your skill set. Use the knowledge areas and  reflect on your own knowledge. Then identify the areas where you lack some knowledge and skills, as I have done in the picture below by high-lightening the areas, which product owners often need to strengthen in my experience.Then rank them by determining how much the lack of knowledge is preventing you from doing a great job. For instance, a lack of product lifecycle management and product roadmap skills may be hurting you most if you manage a product that is in the growth stage. Finally identify how you best close the gap, for instance, reading one or more books, or blogs, attending a training course, finding someone to mentor or coach you, forming a community of practice with your fellow product managers or product owners to share knowledge and support each other. You can do the same exercise for a group of product managers or product owners to identify learning measure for the entire function.Reference: What is Product Management? from our JCG partner Roman Pichler at the Pichler’s blog blog....

Some Sentences about Java

There is nothing new in this article. I just collected some trivial statements which may not be trivial for some of the junior programmers programmers. Boring old stuff. If you happen all of these things you know more about Java than the average house wife. I do not know if there is point to know all of these. You can be a fairly good Java programmer if you do not know some of these features. However a lot of new information in this article probably indicates you have room to develop.         There are 4 different protection types in Java (not three). These are private, package private, protected and public. If you do not specify any protection modifier when you define an element in a class it will be package private (and not public and not protected).  On the other hand if you do not specify protection modifier in front of a method declaration in an interface: it will be public. You may specify it to be explicitly public but it does not have effect on Java and SONAR will not like you doing so.    My opinion about Java allowing you to optionally write public in front of a method in an interface is that this is a technology mistake. Similarly you can write final in front of a field in an interface, or even static. It may imply that they could be non-static or non-final: not true. Fields of an interface are final and static. Always. Protected and package private are not the same Package private (or default) protection will let other classes of the same package access to the method or field. Protected methods and fields can be used from classes in the same package (so far the same as package private) and in addition to that it can be used from other classes that extend the class containing the protected field or method. Protected is transitive If there are three packages a, b and c, each containing a class named A, B and C so that B extends A and C extends B then the class C can access the protected fields and methods of A. package a;public class A { protected void a() {} } package b;import a.A;public class B extends A { protected void b() { a(); } } package c;import b.B;public class C extends B { protected void c() { a(); } } Interface can not define protected methods Many thinks that you can also define protected methods in an interface. When programming the compiler makes it obvious fast and brutally: you can not. Btw: this is why I think that allowing the public keyword in an interface is a technology mistake: it makes people think that it could also be something else as well.  If you want to declare a protected method in an interface, you probably did not understand encapsulation. Private is not that private Private variables and methods are visible inside the compilation unit. If that sounds too cryptic: in the same Java file (almost). This is a bit more than “in the class where they are defined”. They can also be seen from classes and interfaces that are in the same compilation unit. Inner and nested classes can see private fields and methods of the class enclosing them. However enclosing classes can also see the private methods and fields of the classes they enclose down to any depth.     package a;class Private { private class PrivateInPrivate { private Object object; }Object m() { return new PrivateInPrivate().object; } } This latter is not widely known. As a matter of fact it is rarely useful. Private is class level not object If you can access a variable or method you can access it no matter which object it belongs to. If this.a is accessible then another.a is also accessible assumed that another is an instance of the same class. Objects that are instances of the same class can fool around with each others variables or methods. Rarely makes sense to have such a code though. A real life exception is equals() (as generated by Eclipse, lines 15 and 18): package a;public class PrivateIsClass { private Object object;@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PrivateIsClass other = (PrivateIsClass) obj; if (object == null) { if (other.object != null) return false; } else if (!object.equals(other.object)) return false; return true; } } Static classes may have many instancesClasses that are not supposed to have any instances are usually called utility classes. They contain only static fields and static methods and the only constructor is private, not invoked from any of the static methods of the class. In Java 8 you can have such a beasts implemented in interfaces, since Java 8 interfaces can have static methods in it. I am not convinced that we should use that feature instead of utility classes. I am not absolutely convinced that we should use utility classes at all. Static classes are always inside in another class (or interface). They are nested classes. They are static and just as static methods can not access instance methods and fields of the class similarly a static nested class can not access the instance methods and fields of the embedding class. That is because nested classes do not have a reference (pointer if you like) to an instance of the embedding class. Inner classes, as opposed to nested classes are non static and can not be created without an instance of the embedding class. Each instance of an inner class has a reference to exactly one instance of the embedding class and thus an inner class can access instance methods and fields of the embedding class. Because of this you can not create an inner class without an instance of the surrounding class. You need not specify it though if this is the current object, a.k.a this. In that case you can write new, which is, in this case, just a short form for In a static environment, for example from a static method you have to specify which instance of the enclosing class should the inner class created with. See the line 10: package a;class Nesting { static class Nested {} class Inner {} void method(){ Inner inner = new Inner(); } static void staticMethod(){ Inner inner = new Nesting().new Inner(); } } Anonymous classes can access only final variables  When an anonymous class is defined inside a method, it can access local variables if they are final. But saying that is vague. They have to be declared final and they also have to be effective final. This is what is released a bit in Java 8. You need not declare such variables as final but they still have to be effective final.  Why do you need to declare something final, when it has to checked to be like that anyway. Like method arguments. They also have to be final. You say that this is not a requirement of Java? Well, you are right. It is a requirement of programming in good style.Reference: Some Sentences about Java from our JCG partner Peter Verhas at the Java Deep blog....

JPA Entity Graphs

One of the latest features in JPA 2.1 is the ability to specify fetch plans using Entity Graphs. This is useful since it allows you to customise the data that is retrieved with a query or find operation. When working with mid to large size applications is common to display data from the same entity in different and many ways. In other cases, you just want to select a smallest set of information to optimize the performance of your application. You don’t have many mechanisms to control what is loaded or not in a JPA Entity. You could use EAGER / LAZY fetching, but these definitions are pretty much static. You were unable to change their behaviour when retrieving data, meaning that you were stuck with what was defined in the entity. Changing these in mid development is a nightmare, since it can cause queries to behave unexpectedly. Another way to control loading is to write specific JPQL queries. You usually end up with very similar queries and the following methods: findEntityWithX, findEntityWithY, findEntityWithXandY, and so on. Before JPA 2.1, the implementations already supported a non standard way to load data similar to Entity Graphs. You have Hibernate Fetch Profiles, OpenJPA Fetch Groups and EclipseLink Fetch Groups. It was logical to have this kind of behaviour in the specification. It allows you a much finer and detail control on what you need to load using a standard API. Example Consider the following Entity Graph:(Probably the relationships should be N to N, but lets keep it simple). And the Movie Entity has the following definition: @Entity @Table(name = "MOVIE_ENTITY_GRAPH") @NamedQueries({ @NamedQuery(name = "Movie.findAll", query = "SELECT m FROM Movie m") }) @NamedEntityGraphs({ @NamedEntityGraph( name = "movieWithActors", attributeNodes = { @NamedAttributeNode("movieActors") } ), @NamedEntityGraph( name = "movieWithActorsAndAwards", attributeNodes = { @NamedAttributeNode(value = "movieActors", subgraph = "movieActorsGraph") }, subgraphs = { @NamedSubgraph( name = "movieActorsGraph", attributeNodes = { @NamedAttributeNode("movieActorAwards") } ) } ) }) public class Movie implements Serializable { @Id private Integer id;@NotNull @Size(max = 50) private String name;@OneToMany @JoinColumn(name = "ID") private Set<MovieActor> movieActors;@OneToMany(fetch = FetchType.EAGER) @JoinColumn(name = "ID") private Set<MovieDirector> movieDirectors;@OneToMany @JoinColumn(name = "ID") private Set<MovieAward> movieAwards; } Looking closer to the entity, we can see that we have three 1 to N relationships and movieDirectors is set to be Eagerly loaded. The other relationships are set to the default Lazy loading strategy. If we want to change this behaviour, we can define different loading models by using the annotation @NamedEntityGraph. Just set a name to identify it and then use the @NamedAttributeNode to specify which attributes of the root entity that you want to load. For relationships you need to set a name to the subgraph and then use @NamedSubgraph. In detail: Annotations Entity Graph movieWithActors @NamedEntityGraph( name = "movieWithActors", attributeNodes = { @NamedAttributeNode("movieActors") } ) ) This defines an Entity Graph with name movieWithActors and specifies that the relationship movieActors should be loaded. Entity Graph movieWithActorsAndAwards @NamedEntityGraph( name = "movieWithActorsAndAwards", attributeNodes = { @NamedAttributeNode(value = "movieActors", subgraph = "movieActorsGraph") }, subgraphs = { @NamedSubgraph( name = "movieActorsGraph", attributeNodes = { @NamedAttributeNode("movieActorAwards") } ) } ) This defines an Entity Graph with name movieWithActorsAndAwards and specifies that the relationship movieActors should be loaded. Additionally, it also specifies that the relationship movieActors should load the movieActorAwards. Note that we don’t specify the id attribute in the Entity Graph. This is because primary keys are always fetched regardless of what’s being specified. This is also true for version attributes. Hints To use the Entity Graphs defined in a query, you need to set them as an hint. You can use two hint properties and these also influences the way the data is loaded. You can use javax.persistence.fetchgraph and this hint will treat all the specified attributes in the Entity Graph as FetchType.EAGER. Attributes that are not specified are treated as FetchType.LAZY. The other property hint is javax.persistence.loadgraph. This will treat all the specified attributes in the Entity Graph as FetchType.EAGER. Attributes that are not specified are treated to their specified or default FetchType. To simplify, and based on our example when applying the Entity Graph movieWithActors:Default / Specified javax.persistence.fetchgraph javax.persistence.loadgraphmovieActors LAZY EAGER EAGERmovieDirectors EAGER LAZY EAGERmovieAwards LAZY LAZY LAZYIn theory, this should be how the different relationships are fetched. In practice, it may not work this way, because the JPA 2.1 specification also states that the JPA provider can always fetch extra state beyond the one specified in the Entity Graph. This is because the provider can optimize which data to fetch and end up loading much more stuff. You need to check your provider behaviour. For instance Hibernate always fetch everything that is specified as EAGER even when using the javax.persistence.fetchgraph hint. Check the issue here. Query Performing the query is easy. You do it as you would normally do, but just call setHint on the Query object: Hint Entity Graph @PersistenceContext private EntityManager entityManager;public List<Movie> listMovies(String hint, String graphName) { return entityManager.createNamedQuery("Movie.findAll") .setHint(hint, entityManager.getEntityGraph(graphName)) .getResultList(); } To get the Entity Graph you want to use on your query, you need to call the getEntityGraph method on the EntityManager and pass the name. Then use the reference in the hint. Hint must be either javax.persistence.fetchgraph or javax.persistence.loadgraph. Programmatic Annotations may become verbose, especially if you have big graphs or many Entity Graphs. Instead of using annotations, you can programmatically define Entity Graphs. Let’s see how: Start by adding a static meta model Entity Class: @StaticMetamodel(Movie.class) public abstract class Movie_ { public static volatile SingularAttribute<Movie, Integer> id; public static volatile SetAttribute<Movie, MovieAward> movieAwards; public static volatile SingularAttribute<Movie, String> name; public static volatile SetAttribute<Movie, MovieActor> movieActors; public static volatile SetAttribute<Movie, MovieDirector> movieDirectors; } This is not really needed, you can reference the attributes by their string names, but this will give you type safety. Programmatic Entity Graph EntityGraph<Movie> fetchAll = entityManager.createEntityGraph(Movie.class); fetchAll.addSubgraph(Movie_.movieActors); fetchAll.addSubgraph(Movie_.movieDirectors); fetchAll.addSubgraph(Movie_.movieAwards); This Entity Graph specifies that all relationships of the Entity must be loaded. You can now adjust to your own use cases. Resources You can find this sample code in the Java EE samples at Github. Check it here. Extra Note: currently there is a bug in EclipseLink / Glassfish that prevents javax.persistence.loadgraph hint from working properly. Check the issue here. Conclusion Entity Graphs filled a gap missing in the JPA specification. They are an extra mechanism that helps you to query for what you really need. They also help you to improve the performance of your application. But be smart when using them. There might be a better way.Reference: JPA Entity Graphs from our JCG partner Roberto Cortez at the Roberto Cortez Java Blog blog....

Android Tips: On/Off Toggle

When we need to give to users of our apps the ability to switch on/off a given feature, we automatically think of check boxes, toggle buttons or switches:These widgets are available to us out-of-the-box, but then we are constrained to a particular look & feel, which may or may not be what we want in our app. We could customize the switches, but if we’re looking for something entirely different, there are other ways to give users a visual feedback on whether a given feature is enabled or not, for example with plain text and a couple of icons:We could switch from one state to the other by simply touching the text field directly, instead of using buttons, switches or check boxes, with a consistent look & feel across all Android versions. But how? 1. Choose the on/off Icons If we don’t have the icons already, creating those using Android Asset Studio‘s icon generator is fast & easy. 2. Choose the on/off Colors In our Android project’s res/values/colors.xml file:#FFFFFF #FFFFE03. Create the Layout It will be just a clickable TextView with its associated Drawable:Here, the onClick event handler toggleWifi is declared in the XML and will be implemented in the corresponding Activity. 4. Edit the associated Activity //inside Activity //... // field private TextView tvWifi; // flag saved in prefs or db private boolean checkWifi; // colors private static final int COLOR_OFF = R.color.white; private static final int COLOR_ON = R.color.lightyellow; // icons private static final int IC_WIFI_OFF = R.drawable.ic_wifi_off; private static final int IC_WIFI_ON = R.drawable.ic_wifi_on; //... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //... tvWifi = (TextView) findViewById(; // get saved wifi status from db checkWifi = ... setWifi(checkWifi); }//.../** onclick handler */ public void toggleWifi(View view) {//toggle setWifi( ! checkWifi); }/** Sets Wi-fi status + visual feedback */ private void setWifi(boolean onoff){tvWifi.setCompoundDrawablesWithIntrinsicBounds( onoff ? IC_WIFI_ON : IC_WIFI_OFF, 0, 0, 0 );tvWifi.setTextColor( onoff ? getResources().getColor(COLOR_ON) : getResources().getColor(COLOR_OFF));// process.. enable or not WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(onoff); }//... @Override protected void onPause() { super.onPause(); // save checkWifi flag in db //... }//... We can do something similar for as many fields as we wish:Notice that we used a View.onClickListener while defining the onClick() in the XML layout. We could have used a View.OnTouchListener instead: // Activity now implements View.OnTouchListener @Override public void onCreate(Bundle savedInstanceState) { //... tvWifi.setOnTouchListener(this); } //... @Override public boolean onTouch(View v, MotionEvent event) { // handle event here ... return true; } What’s the difference between onClick and onTouch? Not much in this particular use case, since we do not need the extra fancy stuff we could do with onTouch and MotionEvents. This technique is just an alternative way for on/off toggle. We could also easily enhance it with some type of animation. Whether it is “better” or not than regular switches, is mostly a question of taste. It is kind of “non-standard” (whatever that means), but, on the other hand, it might give designers more freedom and abilities to create their own original UIs. Happy Coding !Reference: Android Tips: On/Off Toggle from our JCG partner Tony Sicilian at the Tony’s Blog blog....

How to get rid of focus highlighting in JavaFX

Today I was asked if I know a way to get rid of the focus-highlighting of JavaFX controls (respectively buttons):                  Most posts and tips regarding this issue suggest to add: .button:focused { -fx-focus-color: transparent; } But with this style, a glow like this is still left:To get rid of this glow also often suggested to play around with -fx-background-insets additionally: .button:focused { -fx-focus-color: transparent; -fx-background-insets: -1.4, 0, 1, 2; } But this results in a button rendered with out an outer border:Compared to the default button style:this is still a kind of “highlighting”. Why is that? (And why are there actually 4 inset values ?) Having a look at the JavaFX default style as defined by modena.css bares some more information:/* A bright blue for the focus indicator of objects. Typically used as the * first color in -fx-background-color for the "focused" pseudo-class. Also * typically used with insets of -1.4 to provide a glowing effect. */ -fx-focus-color: #f25f29; -fx-faint-focus-color: #f25f2933;Obviously there is not only one focus color -fx-focus-color but also -fx-faint-focus-color which is meant to create this glow-effect (that remains when setting -fx-focus-color:transparent;). A closer look at the .button:focused pseudo class (in modena.css): .button:focused { -fx-background-color: -fx-faint-focus-color, -fx-focus-color, -fx-inner-border, -fx-body-color; -fx-background-insets: -2, -0.3, 1, 2; -fx-background-radius: 7, 6, 4, 3; } Playing around with some extreme colouring reveals the arrangement: .button:focused { -fx-focus-color: red; -fx-faint-focus-color: green; -fx-inner-border: blue; -fx-body-color: orange;-fx-background-color: -fx-faint-focus-color, -fx-focus-color, -fx-inner-border, -fx-body-color; -fx-background-insets: -2, -0.3, 1, 2; -fx-background-radius: 7, 6, 4, 3; }  Getting back to the topic maybe a clever way to remove the focus highlight is to use the default button styles also for .button:focus (same approach for other controls): .button:focused { -fx-background-color: -fx-outer-border, -fx-inner-border, -fx-body-color; -fx-background-insets: 0, 1, 2; -fx-background-radius: 5, 4, 3; }Reference: How to get rid of focus highlighting in JavaFX from our JCG partner Jens Deters at the JavaFX Delight blog....

Java Code Geeks are giving away FREE copies of their Java Concurrency Essentials eBook!

Want to boost your knowledge on Java Concurrency ? Then we have something especially for you! Enter the contest now to win your very own copy of our Java Concurrency Essentials eBook. Concurrency is always a challenge for developers and writing concurrent programs can be extremely hard. There is a number of things that could potentially blow up and the complexity of systems rises considerably when concurrency is introduced. However, the ability to write robust concurrent programs is a great tool in a developer’s belt and can help build sophisticated, enterprise level applications. With this eBook, you will dive into the magic of concurrency. You will be introduced to the fundamentals of concurrency and concurrent code and you will learn about concepts like atomicity, synchronization and thread safety. Enter the contest now to win your very own FREE copy of the book. In addition, we will send you free tips and the latest news from the Java community to master your technical knowledge (you can unsubscribe at any time). In order to win, you only have to refer at least 2 of your friends to join the contest, and you will ALL win a copy of the book! No draw performed! Make sure to use your lucky URL to spread the word! You can share it on your social media channels, or even mention it on a blog post if you are a blogger! Good luck and may the force be with you! Note: You know we are geeks. You know we can easily find whether you are trying to game the contest. So using your own accounts, like, etc., will get you disqualified. :-)   Join the Contest!   ...

Continuous Delivery: Code Coverage

This article is part of the Continuous Integration, Delivery and Deployment series. In the previous article we explored unit tests as the first and fastest set of tests we should run. Now it’s time to see whether our unit tests provide enough code coverage. Code Coverage Unit tests by themselves do not provide enough confidence unless we know that they cover significant code coverage. Having all tests successful while, for example, covering only 15% of the code cannot provide enough trust. Mature teams might not need to measure code coverage. They might know from experience that their unit tests are covering as much code as the project they’re working on needs. Teams like that tend to have years of practice with Test-driven development (TDD). However, for the majority of us, tools that measure the coverage are very indeed useful addition to our tool-belt. What is code coverage? Code coverage is a measure we’re using to check how much of our source code was tested. The higher the code coverage, the bigger the percentage of our code has been tested. Important thing to understand is that the code coverage is not directly related with code quality. High code coverage does not guarantee high quality of those tests. For example, even with 100% of code coverage there is no guarantee that certain functionality was developed correctly nor that it was developed at all. While code coverage can be used with any type of testing, it is most common and useful to tie it to unit tests. Integration and functional tests can be measured as well but the expectations from results must be different. For more information please consult Code and Test Coverage. Let’s see how we can implement code coverage in our CI/CD tools. Jenkins For those of you who did not follow the previous articles in detail or those who failed to reproduce all exercises, please install Vagrant and clone the code from the repository TechnologyConversationsCD. To create a virtual machine with Jenkins and myFirstJob job that performs static analysis, please go to the directory servers/jenkinsWithTests inside the cloned repository and execute the following: vagrant up If this is not the first time you’re starting this vagrant VM (“vagrant up” is configured to run the Docker container only the first time) or for some reason Docker container is not running, it can be run with the following shortcut script. /opt/ We can check which containers are running by executing: docker ps When finished, virtual machine with Jenkins and myFirstJob job will be up and running. Results can be seen by opening http://localhost:8080 in browser. We’ll continue using Gradle as our build tool. In the last article we were executing the Gradle task check to run static analysis (CheckStyle, FindBugs and PMD) and tests. Now we’ll add Code Coverage with JaCoCo. To add JaCoCo code coverage all that should be done is add the plugin to the build.gradle file. apply plugin: 'jacoco'Good news is that if JaCoCo plugin is used, it adds itself to Gradle tasks check and test. Since we already have Jenkins job that runs Gradle check task, there’s nothing to be done to tell JaCoCo to collect statistics of our tests. However, JaCoCo needs two executions. One is to start collecting data from our tests (already covered within the Gradle check task). The second one is to generate HTML report from collected data. In order to do that, we should change our Gradle invocation from the Jenkins job myFirstJob by adding jacocoTestReport to the list of Gradle tasks. Now it should look like:   clean check jacocoTestReportTo publish JaCoCo coverage reports, we’ll need to install the JaCoCo plugin (Jenkins > Manage Jenkins > Manage Plugins > Available). Once the plugin is installed, we can add the post-build action called “Record JaCoCo coverage report”. As “Path to exec files” put “/.exec” (JaCoCo saves coverage data to an .exec file). “Path to class directories” should be set to “/classes” so that all those previously compiled with Gradle are included. Finally, we should set “Path to source directories” to “/src/main/java”. The rest of parameters are related to coverage health and depends on team preferences. I tend to consider code coverage of 90% acceptable. More than 95% is often counter productive.That’s it. We’re ready to build the myFirstJob with JaCoCo code coverage included. Press “Build Now” button1 from the left-hand menu. Once job execution is finished, enter the build and click the “Coverage Report”. It will show the report with coverage of instructions, branches, complexity, lines, methods and classes. Integrating JaCoCo inside Jenkins is fairly easy. Hard part is to get to the point where code coverage through tests is reasonably high. Having a firm grasp of TDD and functional and integration testing (my preference is BDD) is the key.     Travis Travis does not play well with JaCoCo. Sure, it’s easy to run it through Gradle in the same way as we did with Jenkins. However, there is no easy way to obtain and publish results. In case of test results, inability to publish is not a problem since we are interested only whether there is some failed test and can easily see from logs which one failed. Since failed tests should be fixed as soon as possible, there is no real reason for reports. Code coverage is different. Since in most cases code coverage obtained through tests is not 100%, ability to see and review the results in important. CircleCI As with Travis, CircleCI does not require anything special to be done to run code coverage since it is part of the Gradle task check (assuming that we added JaCoCo Gradle plugin). We already saw in the previous article that Circle is very similar to Travis in its approach to CI. Major difference was in the stability and speed (it is several times faster than Travis). With code coverage we can explore another difference. Circle has the option to store build artifacts. With them we can accomplish the similar effect as what we did with Jenkins. We’ll allow users to see the Gradle code coverage together with other types of reports. All we need to do is to modify our circle.yml file by adding jacocoTestReport and making sure that all reports are added to CircleCI artifacts. [circle.yml] test: override: - gradle check jacocoTestReport post: - cp -R build/reports/* $CIRCLE_ARTIFACTS Full source code can be found in the circle.yml. Once this change is pushed to the repository CircleCI will store all our reports and make them available through the “Artifacts” option available in each build. By opening jacoco/test/html/index.html we can see the nice report JaCoCo generated for us. Summary It was fairly easy to set up code coverage and publish results in both Jenkins and CircleCI. The only thing we had to do was to tell them to run Gradle task jacocoTestReport and where to find the results. Travis, on the other hand, does not have an option to publish reports. Without them code coverage is next to useless. Jenkins continues to shine with its plugin system. Circle’s “Build Artifacts” was a pleasant surprise and another handy addition to its speed. The more I’m using it, the more I can see the advantages when compared to Travis. Travis’ price was unbeatable (public repositories are free). However, since recently CircleCI is free as well while providing faster builds and several nice additions (like storing artifacts). In the next article we’ll explore the final stage of the continuous delivery and deployment. The goal is to continuously deploy (or at least deliver) software. Continous in this case means often, fast and with zero downtime. Stay tuned.  Word of caution: make sure to wipe the workspace ([JOB] > Workspace > Wipe Out Current Workspace) if running the same build multiple times without actually making any changes to the code. Gradle will detect that there are no changes and do nothing. This is a good thing since that way a lot of time can be saved but it can cause a bit of confusion when testing Jenkins job configuration. Reference: Continuous Delivery: Code Coverage from our JCG partner Viktor Farcic at the Technology conversations blog....

It’s All About Tests – Part 3

In the previous two posts I discussed mostly about the philosophy and attitude of developing with testing. In this post I give some tips and tools examples for testing. Tools JUnit There’s also TestNG, which is great tool. But I have much more experience with JUnit so I will describe this framework.  Use the latest version. Know your testing tool!@RunWith This is class annotation. It tells JUnit to run with different Runner (mockito and Spring runners are the most common runners I use) import org.mockito.runners.MockitoJUnitRunner; ... @RunWith(MockitoJUnitRunner.class) public class MyClassTest { ... } @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/META-INF/app-context.xml","classpath:anotherContext.xml" }) public class MyClassTest { ... } // You can inherit AbstractJUnit4SpringContextTests instead of using runner@Rule kind of AOP. The most common out-of-the-box rule, is the TemporaryFolder Rule. It lets you use the file system without worrying about opening and closing files. An example of Rules can be found here. Parameterized runner Really cool tool. It lets you run the same test with different input and different expected output. It might be abused and make a atest unreadable. Test Data Preparation and Maintenance Tipshamcrest This library is “extension” of JUnit. I can’t work without it! Hamcrest library gives us out-of-the-box matchers. Matchers are used with the assertThat(...,Matcher) flavor. I almost always use this flavor. (In the previous post, someone suggested that I shouldn’t use assertTrue(…), but instead use assertThat). There are plenty type of matchers: You can verify existing objects in collection ignoring order. You can check greater than. The test is more readable using the assertThat + matcher. assertThat(mapAsCache.containsKey(new CacheKey("valA", "valB")), is(true)); assertThat(cachPairs.size(), is(2)); assertThat(enity.getSomething(), nullValue(Double.class)); assertThat(event.getType(), equalTo(Type.SHOWN)); assertThat(bits, containsInAnyOrder(longsFromUsIndexOne, longsFromUsIndexZero)); You can create your own Matcher. It’s very easy. Here’s an example of matchers that verify Regular Expressions. mockito This is the second library I can’t work without. It lets you mock dependencies of the class under test. Using mockito you mock dependency. Then you “tell” the mock object how to behave in certain inputs. You tell it what to return if some input entered. You can verify input arguments to a called method. You can verify that a certain method was called (once, never, 3 times, etc.). You can check the order of method / mocks calls. Check this out: package eyalgo; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; //The RunWith automatically instantiate fields with @Mock annotation //and injects to the tested class @InjectMocks @RunWith(MockitoJUnitRunner.class) public class NameConnectorTest { @Mock private NameConvention nameConventionAsMockField; @InjectMocks private NameConnector connector; private NameConvention nameConventionAsMockOther; @Before public void setup() { //This is another way to inject mocks (instead of the annotations above) MockitoAnnotations.initMocks(this); nameConventionAsMockOther = mock(NameConvention.class); NameConnector otherConnector = new NameConnector(nameConventionAsMockOther); } @Test public void showSomeMockitoExamples() { NameConvention nameConventionAsMock = mock(NameConvention.class, "Name for this mock"); // Stub and tell your mock to do something when(nameConventionAsMock.bigBangConvention("INPUT")).thenReturn("Some output"); // Throw exception for some input when(nameConventionAsMock.bigBangConvention("Other INPUT")).thenThrow(new RuntimeException("oops")); // Do more complicated stuff in the "when" Answer answer = new Answer() { @Override public String answer(InvocationOnMock invocation) throws Throwable { //do something really complicated return "some output"; } }; //Show also hamcrest matchers when(nameConventionAsMock.bigBangConvention(argThat(equalTo("my name is Inigo Montoya")))).then(answer); // Run the test.. //Verify some calls verify(nameConventionAsMock).bigBangConvention("INPUT"); verify(nameConventionAsMock, times(10)).bigBangConvention("wow"); // Verify that the method was never called. With any input verify(nameConventionAsMock, never()).bigBangConvention(anyString()); verifyNoMoreInteractions(nameConventionAsMock); verifyZeroInteractions(nameConventionAsMockField); //Check order of calls InOrder order = inOrder(nameConventionAsMock, nameConventionAsMockOther); order.verify(nameConventionAsMock).bigBangConvention("INPUT"); order.verify(nameConventionAsMock).bigBangConvention("other INPUT"); } } Other Mocking ToolsPowerMock and EasyMock These two are very useful when working with legacy code. They allow you to test private methods, static methods and more things that you normally can’t. I think that if you need them, then something is wrong with the design. However, sometimes you use external libraries with singletons and/or static methods. Sometimes you work on legacy code, which is not well suited for testing. On these types of scenarios, then those mocking libraries can help JMockit jMock JUnit, mockito, hamcrest are used for unit tests. JBehave is not exactly the same. It is a tool for Behavior-Driven-Development (BDD) You write stories which are backed up by code (Java) and then you run them. JBehave can be used for higher level tests, like functional tests. Using JBehave, it’s easier to test a flow in the system. It follows the Given, When, Then sequence. If you take it to the next step, it can be a great tool for communication. The product owner can write the scenarios, and if all is green, by the end of the iteration, then we passed the definition of done. cucumber is another BDD tool. Dependency Injection In order to have testable code, among other things, you need to practice DI (dependency injection). The reason is simple: If you instantiate a dependency in a constructor (or method) of a class under test, then how can you mock it? If you can’t mock the dependency, then you are bound to it. And you can’t simulate different cases. Many application have Spring as the DI container, but less developers take the advantage of using the injection for testing. Metrics Use SONAR in your CI environment. Check code coverage using cobertura or other tools. Use Jenkins / Hudson / Other CI tool for automation. IDE Your IDE can help you writing tests. For eclipse, I have two recommendations:MoreUnit is cool plugin that helps writing tests faster. In eclipse, CTRL+Space can give you hints and fill imports. But not static imports. Most (all?) libraries use static imports. So you can add the testing libraries as favorites and then eclipse will fill them for you.  POM Here’s part of POM for testing libraries. <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <addMavenDescriptor>false</addMavenDescriptor> </archive> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>com.startapp.CouchRunner.GetUserProfile</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> </plugins> </build> You can check the order of method / mocks calls. You can use profiles to separate unit testing with integration tests.Reference: It’s All About Tests – Part 3 from our JCG partner Eyal Golan at the Learning and Improving as a Craftsman Developer blog....

Unit Testing exercise with FizzBuzz and Mockito

I sometimes use FizzBuzz to demonstrate the basics of unit testing to newbies. Although FizzBuzz is really simple problem, it can also be used to demonstrate more advanced unit testing techniques like mocking. The FizzBuzz Kata: “Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”“.The possible solution to FizzBuzz algorithm: public class FizzBuzz {private static final int FIVE = 5; private static final int THREE = 3;public String calculate(int number) {if (isDivisibleBy(number, THREE) && isDivisibleBy(number, FIVE)) { return "FizzBuzz"; }if (isDivisibleBy(number, THREE)) { return "Fizz"; }if (isDivisibleBy(number, FIVE)) { return "Buzz"; }return "" + number; }private boolean isDivisibleBy(int dividend, int divisor) { return dividend % divisor == 0; } } As the above code solves the FizzBuzz algorithm it does not solve the FizzBuzz problem. To finish it we need code to print the numbers from 1 to 100 using the algorithm. And this part of the code can be used to show the idea of mocking in JUnit with Mockito. As the result of this exercise I ended up with a NumberPrinter that takes two arguments: Printer and NumberCalculator and has one public method to print numbers: public class NumberPrinter {private NumberCalculator numberCalculator; private Printer printer;public NumberPrinter(NumberCalculator numberCalculator, Printer printer) { this.numberCalculator = numberCalculator; this.printer = printer; }public void printNumbers(int limit) { if (limit < 1) { throw new RuntimeException("limit must be >= 1"); } for (int i = 1; i <= limit; i++) { try { printer.print(numberCalculator.calculate(i)); } catch (Exception e) { // noop } } } }public interface NumberCalculator { String calculate(int number); }public interface Printer { void print(String s); } With the interfaces introduced I have not only testable but more robust code. To test NumberPrinter I simply mock dependencies with the power and simplicity of Mockito. With Mockito annotations the configuration test code reads better. Mockito features demonstrated:creating and injecting mocks stubbing methods also with setting different behavior for consecutive method calls. stubbing the void method with an exception verificationsAnnotations used:@RunWith(MockitoJUnitRunner.class) – initializes @Mocks before each test method @Mock – marks a field as mock @InjectMocks – marks a field on which injection should be performed@RunWith(MockitoJUnitRunner.class) public class NumberPrinterTest {@Mock private Printer printer;@Mock private NumberCalculator numberCalculator;@InjectMocks private NumberPrinter numberPrinter;@Test public void printsCalculatorResultsHundredTimes() { // arrange int limit = 100; when(numberCalculator.calculate(anyInt())) .thenReturn("0") // first invocation returns "0" .thenReturn("1"); // other invocations return "1" // act numberPrinter.printNumbers(limit); // assert verify(numberCalculator, times(limit)).calculate(anyInt()); verify(printer, times(1)).print("0"); verify(printer, times(limit - 1)).print("1"); verifyNoMoreInteractions(numberCalculator, printer); }@Test public void continuesOnCalculatorOrPrinterError() { // arrange when(numberCalculator.calculate(anyInt())) .thenReturn("1") .thenThrow(new RuntimeException()) .thenReturn("3"); // stub the void method with an exception doThrow(new RuntimeException()).when(printer).print("3"); // act numberPrinter.printNumbers(3); // assert verify(numberCalculator, times(3)).calculate(anyInt()); verify(printer).print("1"); verify(printer).print("3");verifyNoMoreInteractions(numberCalculator, printer); } } Enjoy Mockito!Want to learn more about Mockito annotations? Have a look at Eugen Paraschiv’s “Mockito – @Mock, @Spy, @Captor and @InjectMocks”: for code samples? Have a look at unit-testing-demo project presenting different aspects of unit testing, including mocking: Unit Testing exercise with FizzBuzz and Mockito from our JCG partner Rafal Borowiec at the blog....
Java Code Geeks and all content copyright © 2010-2015, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.