Skip to content

Feed aggregator

Guide to Separate JRE Versions From NetBeans Platform Installer

In an enterprise set up where updating Java on a client machine is not allowed due to software restriction policy, it becomes challenging to develop and ship applications which require the latest version of Java to be installed on client machines. One way to circumvent this policy-based restriction is to bundle the JREs for 32-bit and 64-bit Windows OS in a separate NetBeans platform installer. This ensures that the JRE remains isolated from the system and conflict with any older version of Java is avoided. This method is detailed in an excellent article written by  Ernest Lotter.

However, the bundling of JRE with the application forces you to maintain separate copies of the installer for 32-bit and 64-bit versions of Java. It also ties the application with the version of Java which was available at that point in time. In a scenario where development and improvement is a continuous process, one would love to have the flexibility of using the latest Java features in the application being developed and at the same time be able to deliver the latest version of Java to client machines.

Categories: Communities

Java 9 (Part 4): Trying Try-with-Resources: First Look

This is part 4 of the java 9 series. While in part 3 we covered interfaces and the private methods that were added to them, in part 4 we see that try-with-resoures was enhanced, or we might say even fixed. Try-with-resources, which was introduced back in java 7, is a concept which helps developer close resources which are not using anymore, such as database connection, file streams, etc. Let‚Äôs see how try-with-resources behaved in java 7 and now in java 9.

Step 1: Pre-Java 7 Try-with-Resources

Try-with-Resources, prior to Java 9, meant that instead of just calling a piece of code which opens up a resource like:

Categories: Communities

Java 9 (Part 3): Super Interfaces, First Look!

In Scala, traits can have an implementation, so why not have implementations in Java? Well, that was introduced in Java 8, so the next natural step in Java 9 is to have private logic in interfaces. In Part 2 of this series, we introduced the Java 9 REPL. In this part, we are going to examine the new functionality introduced to interfaces.

Java 9 is introducing a lot of new concepts, such as REPL, factory methods for common data structures, and more. Let’s see what Java 9 has to say about private methods in interfaces.

Categories: Communities

Arbitrary Precision Numbers

I am working on a system that involves money handling, written in Java. And as you can imagine, one of the challenges is to make sure that money is not appearing or disappearing because of the floating point arithmetic. I asked a few developers how to handle money and one common answer was to use BigDecimal for that. Therefore, I performed a few experiments on the side and discovered few things that you probably won't see after the first look into this class. In this article, I am going to show these discoveries together with the final solution I decided to go with.

Rounding Errors

Before going into the detailed explanation, let's create an example that shows what happens with floating point numbers. Imagine you want to split $200 between four people. First, two of them will get 1/3 and the other two will get 1/6. Then let's see what happens when you put these parts back together. The following code demonstrates the situation (using Lenovo Yoga, Win 8.1, Java 1.8).

Categories: Communities

Spring Transaction Management Over Multiple Threads

The Spring framework provides a comprehensive API for database transaction management. Spring takes care of all underlying transaction management considerations and provides a consistent programming model for different transaction APIs such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO). There are two main types of transaction management in Spring: declarative transaction management, which is a high level one, and programmatic transaction management, which is more advanced but flexible.

The Spring API works very well with almost all of the transaction management requirements as long as the transaction is on a single thread. The problem arises when we want to manage a transaction across multiple threads. Spring doesn't support transactions over multiple threads out of the box. Spring doesn't explicitly mention that in the documentation, but you will end up with runtime errors or unexpected results if you try to do so.

Why Do Spring Transactions Over Multiple Threads Fail?

Spring stores a set of thread locals inside the class. These thread locals are specific for an ongoing transaction on a single thread (Thread locals values are specific for a single thread. Thread local value set by one thread cannot be accessed by another thread).

Categories: Communities

Fixing My Own Spring Boot Starter Demo

For one year or so, I've been trying to show the developer community that there‚Äôs no magic involved in Spring Boot, just straightforward software engineering. This is achieved with blog posts and conference talks. At jDays, Stéphane Nicoll was nice enough to attend my talk and pointed out an issue in the code. I didn‚Äôt fix it then, and it came back to bite me last week during a Pivotal webinar. Since a lesson learned is only as useful as its audience, I‚Äôd like to share my mistake with the world, or at least with you, dear readers.

The context is that of a Spring Boot starter for the XStream library: XStream is a simple library to serialize objects to XML and back again.

Categories: Communities

Servlet 4 Public Review Starts Now!

Servlet 4 has just posted a public review (this is the last step before the proposed final specification). Servlet 4 is easily one of the most critical components of Java EE 8. The primary aim of Servlet 4 is to bring first-class, core standards based HTTP/2 support to the server-side Java ecosystem. Most of the changes in Servlet 4 (with the exception of things like the server push API) should be transparent to developers and are enforced in terms of requirements for Servlet 4 implementations to fully support HTTP/2. A decent resource to learn more about Servlet 4 and HTTP/2 should be my slide deck:

HTTP/2 and What it Means for the Java EE Ecosystem from Reza Rahman.

You can download and take a look at the draft specification itself from the JCP site. While this is essentially the final stretch for Servlet 4, below are some ways you can still engage; most of it comes directly from the Adopt-a-JSR page I drafted while still at Oracle. The Servlet 4 specification lead Ed Burns has also asked for specific help in testing out the server-push feature. His write-up is also a great introduction to the feature.

Categories: Communities

Custom UI Components in Oracle ABCS for Dynamic Image Display

Shay Shmeltzer's Weblog - Mon, 04/24/2017 - 23:29

This quick one is based on a customer question about Oracle Application Builder Cloud Service. The scenario is that we have a business object that has a field that contains the URL to an image. We want to be able to show that image on a page in Oracle Application Builder Cloud Service.

animated GIF

To do that I add a custom UI component object to the details (or edit) page of a record - then I switched the HTML of that object to be: <img id="logoimg"/>

custom code

I then added a button to the page and added a bit of custom JavaScript code in its action as follow:

var img = document.getElementById('logoimg');



This code simply locates the custom object on the page using the object id and then sets the src property of the img html tag to match the value of the field in the business object.

Code in Button

Categories: Companies

Gradle Goodness: Using the Incremental Task Action

Gradle has incremental build support to speed up our builds. This means Gradle checks inputs and outputs for a task, and if something changed, the task is executed. Otherwise, the task is skipped. In previous posts, we learned how to add incremental build support to our tasks with annotations and the inputs and outputs properties of a task. When we have a task that has an output file for an input file, like with transformations, we can have a more efficient task using an incremental task action. With an incremental task action, we have extra information on the files that are handled by the task. We can have different actions based on whether an input file is out of date or removed. This way, we can handle only the input files that have changed or removed with incremental builds, instead of all the input files.

To create an incremental task action, we must have a task action method (annotated with @TaskAction) that has a single argument of type IncrementalTaskInputs. The IncrementalTaskInputs class has the method outOfDate and removed. These methods take an action, which can be implemented with a closure, with an instance of InputFileDetails as the argument. We can get to the input file via this instance and use that for our task logic. When an input file is out of date, because the file's contents have changed or the output file has been removed, the action we defined for the outOfDate method is invoked. If the input file is removed, the action for the method removed is invoked.

Categories: Communities

Guide to @ConfigurationProperties in Spring Boot

baeldung - Coding and Testing Stuff - Mon, 04/24/2017 - 18:58
1. Introduction

One of the handy features of Spring Boot is externalized configuration and easy access to properties defined in properties files.

An earlier article described various ways in which this can be done and in this article, we’re going to explore the @ConfigurationProperties annotation in greater detail.

2. Setup

The setup for this article is fairly standard. We start by adding spring-boot-starter-parent as the parent in our pom.xml:

<!-- Inherit defaults from Spring Boot -->
    <relativePath/> <!-- lookup parent from repository -->

The latest version of Spring Boot can be found on the maven central here.

In order to be able to validate properties defined in the file, we would need a JSR-303’s implementation. hibernate-validator is one of them. Let’s add it to our pom.xml as well:


Depending on the type of application and the environment running, we might need to add one or more additional dependencies. The reference page has details about the same, and the latest version of hibernate-validator can be found here.

We shall take the example of a hypothetical class which has configuration properties related to a mail server to understand the full power of this annotation:

public class ConfigProperties {

    public static class Credentials {
        private String authMethod;
        private String username;
        private String password;

       // standard getters and setters
    private String host;
    private int port;
    private String from;
    private Credentials credentials;
    private List<String> defaultRecipients;
    private Map<String, String> additionalHeaders;
    // standard getters and setters
3. Binding the Configuration Properties

According to the official documentation, it is recommended to isolate the configuration properties into a separate POJO¬†annotated with @ConfigurationProperties, so let’s start by doing that:

public class ConfigProperties {
    // previous code

We also have added the @Configuration annotation for Spring to be able to find this bean and make it a candidate for injection.

The annotation works best when we have hierarchical properties that all have the same prefix, so we mention the prefix too as a part of the annotation. We can also optionally define a custom source where we’re storing these properties, else the default location (

We can also optionally define a custom source where we’re storing these properties, else the default location ( is¬†looked up. So we now add the above annotations to the existing properties class:

@ConfigurationProperties(prefix = "mail")
public class ConfigProperties {
    // previous code

That’s it! Now any properties defined in the property file that has the prefix mail and the same name as one of the properties are automatically assigned to this object.

Also, by default, a relaxed binding scheme is adopted for the binding, so all of the following variations are bound to the property authMethod of the Credentials class:


Similarly, List and Map properties can also be bound. Here’s a sample properties file that binds correctly to our ConfigProperties object defined earlier:

#Simple properties

#List properties

#Map Properties

#Object properties
4. Property Validation 

One of the handy things that this annotation provides the is the validation of properties using the JSR-303 format. This allows for all sorts of neat things like checking that a property is not null:

private String host;

We can also check the minimum and maximum length of a String property:

@Length(max = 4, min = 1)
private String authMethod;

Or enforce the minimum and maximum value of an Integer property:

private int port;

And finally, we can also make sure that a property matches a certain pattern by defining a regex for the same. This has been done for email, as an example:

@Pattern(regexp = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,6}$")
private String from;

This helps us reduce a lot of if – else conditions in our code and makes it look much cleaner and concise.

If any of these validations fail then the main application would fail to start with an IllegalStateException till the incorrect property is corrected.

Also, it is important that we declare getters and setters for each of the properties as they’re used by the validator framework to access the concerned properties.

5. Conclusion

In this quick tutorial, we explored the @ConfigurationProperties annotation and also saw some of the handy features it provides like relaxed binding and Bean Validation.

As usual, the code is available over on Github.

Categories: Blogs

The Biggest Change To Java

To gather insights on the state of the Java ecosystem today, we spoke to nine executives who are familiar with the ecosystem.

We asked these experienced Java professionals "What have been the most significant changes to the Java ecosystem in the past year?" Here's what they told us:

Categories: Communities

Spring Boot, @EnableWebMvc, and Common Use Cases

It turns out that Spring Boot doesn’t mix well with the standard Spring MVC @EnableWebMvc. What happens when you add the annotation is that Spring Boot's autoconfiguration is disabled.

The bad part (that wasted me a few hours) is that in no guide you can find that explicitly stated. In this guide, it says that Spring Boot adds it automatically, but doesn’t say what happens if you follow your previous experience and just put the annotation.

Categories: Communities

Logout in a OAuth Secured Application

baeldung - Coding and Testing Stuff - Mon, 04/24/2017 - 15:39
1. Overview

In this quick tutorial, we’re going to show how we can add logout functionality to an OAuth Spring Security application.

We’ll, of course, use the OAuth application described in a previous article – Creating a REST API with OAuth2.

2. Remove the Access Token

Simply put, logging out in an OAuth-secured environment involves rendering the user’s Access Token invalid – so it can no longer be used.

In a JdbcTokenStore-based implementation, this means removing the token from the TokenStore.

Let’s implement a delete operation for the token. We’re going to use the parimary /oauth/token URL structure here and simply introduce a new DELETE operation for it.

Now, because we’re actually using the /oauth/token URI here – we need to handle it carefully. We won’t be able to simply add this to any controller – because the framework already has operations mapped to that URI – with POST and GET.

Instead what we need to do is to define this is a @FrameworkEndpoint – so that it gets picked up and resolved by the FrameworkEndpointHandlerMapping instead of the standard RequestMappingHandlerMapping. That way we won’t run into any partial matches and we won’t have any conflicts:

public class RevokeTokenEndpoint {

    @Resource(name = "tokenServices")
    ConsumerTokenServices tokenServices;

    @RequestMapping(method = RequestMethod.DELETE, value = "/oauth/token")
    public void revokeToken(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.contains("Bearer")){
            String tokenId = authorization.substring("Bearer".length()+1);

Notice how we’re extracting the token out of the request, simply using the standard Authorization header.

3. Remove the Refresh Token

In a previous article on Handling the Refresh Token we have set up our application to be able to refresh the Access Token, using a Refresh Token. This implementation makes use of a Zuul proxy – with a CustomPostZuulFilter to add the refresh_token value received from the Authorization Server to a refreshToken cookie.

When revoking the Access Token, as shown in the previous section, the Refresh Token associated with it is also invalidated. However, the httpOnly cookie will remain set on the client, given that we can’t remove it via JavaScript – so we need to remove it from the server side.

Let’s enhance the CustomPostZuulFilter implementation that intercepts the /oauth/token/revoke URL so that it will remove the refreshToken cookie when encountering this URL:

public class CustomPostZuulFilter extends ZuulFilter {
    public Object run() {
        String requestMethod = ctx.getRequest().getMethod();
        if (requestURI.contains("oauth/token") && requestMethod.equals("DELETE")) {
            Cookie cookie = new Cookie("refreshToken", "");
            cookie.setPath(ctx.getRequest().getContextPath() + "/oauth/token");
4. Remove the Access Token from the AngularJS Client

Besides revoking the access token from the token store, the access_token cookie will also need to be removed from the client side.

Let’s add a method to our AngularJS controller that clears the access_token cookie and calls the /oauth/token/revoke DELETE mapping:

$scope.logout = function() {
function logout(params) {
    var req = {
        method: 'DELETE',
        url: "oauth/token"

This function will be called when clicking on the Logout link:

<a class="btn btn-info" href="#" ng-click="logout()">Logout</a>
5. Conclusion

In this quick but in-depth tutorial, we’ve shown how we can logout a user from an OAuth secured application and invalidate the tokens of that user.

The full source code of the examples can be found over on GitHub.

Categories: Blogs

GlassFish v5 (Java EE 8 RI)--Docker Image Is Available

Adam Bien's Weblog - Mon, 04/24/2017 - 11:06

GlassFish v5 ea (Java EE 8) builds available for download:

The nightly build is also available from docklands as glassfish5 and glassfish5-ping Dockerfiles.

Binary images are directly available from the public docker registry:

To start glassfishv5 perform docker run -d -p 8080:8080 --name glassfishv5 airhacks/glassfish-ping

The ping should be availabe after ~3 secs under: http://localhost:8080/ping.

See you at Java EE Microservices. Is Munich's airport too far? Learn from home:
Real World Java EE Workshops [Airport Munich]>
Categories: Blogs

A Guide to Java SynchronousQueue

baeldung - Coding and Testing Stuff - Mon, 04/24/2017 - 10:41
1. Overview

In this article, we’ll be looking at the¬†SynchronousQueue¬†from the java.util.concurrent¬†package.

Simply put, this implementation allows us to exchange information between threads in a thread-safe manner.

2. API Overview

The SynchronousQueue only has two supported operations: take() and put(), and both of them are blocking.

For example, when we want to add an element to the queue, we need to call the put() method. That method will block until some other thread calls the take() method, signaling that it is ready to take an element.

Although the SynchronousQueue has an interface of a queue, we should think about it as an exchange point for a single element between two threads, in which one thread is handing off an element, and another thread is taking that element.

3. Implementing Handoffs Using a Shared Variable

To see why the SynchronousQueue can be so useful, we will implement a logic using a shared variable between two threads and next, we will rewrite that logic using SynchronousQueue making our code a lot simpler and more readable.

Let’s say that we have two threads – a producer and a consumer – and when the producer is setting a value of a shared variable, we want to signal that fact to the consumer thread. Next, the consumer thread¬†will fetch a value from a shared variable.

We will use the CountDownLatch to coordinate those two threads, to prevent a situation when the consumer accesses a value of a shared variable that was not set yet.

We will define a sharedState variable and a CountDownLatch that will be used for coordinating processing:

ExecutorService executor = Executors.newFixedThreadPool(2);
AtomicInteger sharedState = new AtomicInteger();
CountDownLatch countDownLatch = new CountDownLatch(1);

The producer will save a random integer to the sharedState variable, and execute the countDown() method on the countDownLatch, signaling to the consumer that it can fetch a value from the sharedState:

Runnable producer = () -> {
    Integer producedElement = ThreadLocalRandom

The consumer will wait on the countDownLatch using the await() method. When the producer signals that the variable was set, the consumer will fetch it from the sharedState:

Runnable consumer = () -> {
    try {
        Integer consumedElement = sharedState.get();
    } catch (InterruptedException ex) {

Last but not least, let’s¬†start our program:


executor.awaitTermination(500, TimeUnit.MILLISECONDS);
assertEquals(countDownLatch.getCount(), 0);

It will produce the following output:

Saving an element: -1507375353 to the exchange point
consumed an element: -1507375353 from the exchange point

We can see that this is a lot of code to implement such a simple functionality as exchanging an element between two threads. In the next section, we will try to make it better.

4. Implementing Handoffs Using the SynchronousQueue

Let’s now¬†implement the same functionality as in the previous section, but with¬†a SynchronousQueue. It has a double¬†effect because we can use it for exchanging state between threads and for coordinating that action so that we don’t need to use anything besides SynchronousQueue.

Firstly, we will define a queue:

ExecutorService executor = Executors.newFixedThreadPool(2);
SynchronousQueue<Integer> queue = new SynchronousQueue<>();

The producer will call a put() method that will block until some other thread takes an element from the queue:

Runnable producer = () -> {
    Integer producedElement = ThreadLocalRandom
    try {
    } catch (InterruptedException ex) {

The consumer will simply retrieve that element using the take() method:

Runnable consumer = () -> {
    try {
        Integer consumedElement = queue.take();
    } catch (InterruptedException ex) {

Next, we will start our program:


executor.awaitTermination(500, TimeUnit.MILLISECONDS);
assertEquals(queue.size(), 0);

It will produce the following output:

Saving an element: 339626897 to the exchange point
consumed an element: 339626897 from the exchange point

We can see that a SynchronousQueue is used as an exchange point between the threads, which is a lot better and more understandable than the previous example which used the shared state together with a CountDownLatch.

5. Conclusion

In this quick tutorial, we looked at the SynchronousQueue construct. We created a program that exchanges data between two threads using shared state, and then rewrote that program to leverage the SynchronousQueue construct. This serves as an exchange point that coordinates the producer and the consumer thread.

The implementation of all these examples and code snippets can be found in the GitHub project ‚Äď this is a Maven project, so it should be easy to import and run as it is.

Categories: Blogs

Using CDI With Java EE Concurrency Utilities

This blog post explores the usage of CDI along with Java EE Concurrency Utilities ‚Äď specifically using CDI beans as managed tasks. Here is the sample application on GitHub.

Let's Begin With a Quick Overview

Java EE Concurrency Utilities provides APIs and constructs to manage concurrency within Java EE applications. Many of the Java EE components have specific concurrency semantics e.g. EJBs, JAX-RS resources, WebSocket endpoints, etc. Writing components with custom concurrency properties was traditionally difficult, since starting unmanaged threads in a Java EE container was forbidden, i.e. one was not able to leverage Java SE concurrency libraries. With Concurrency Utilities, Java EE applications have access to managed versions of the Java SE counterparts, namely,

Categories: Communities

Create a Custom Auto-Configuration with Spring Boot

baeldung - Coding and Testing Stuff - Sun, 04/23/2017 - 17:54
1. Overview

Simply put, the Spring Boot autoconfiguration represents a way to automatically configure a Spring application based on the dependencies that are present on the classpath.

This can make development faster and easier by eliminating the need for defining certain beans that are included in the auto-configuration classes.

In the following section, we’re going to take a look at creating our custom Spring Boot auto-configuration.

2. Maven Dependencies

Let’s start with the dependencies that we need:


The latest versions of spring-boot-starter-data-jpa and mysql-connector-java can be downloaded from Maven Central.

3. Creating a Custom Auto-Configuration

To create a custom auto-configuration, we need to create a class annotated as @Configuration and register it.

Let’s create a custom configuration for a MySQL data source:

public class MySQLAutoconfiguration {

The next mandatory step is registering the class as an auto-configuration candidate, by adding the name of the class under the key org.springframework.boot.autoconfigure.EnableAutoConfiguration in the standard file resources/META-INF/spring.factories:


If we want our auto-configuration class to have priority over other auto-configuration candidates, we can add the @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) annotation.

Auto-configuration is designed using classes and beans marked with @Conditional annotations so that the auto-configuration or specific parts of it can be replaced.

Note that the auto-configuration is only in effect if the auto-configured beans are not defined in the application. If you define your bean, then the default one will be overridden.

3.1. Class Conditions

Class conditions allow us to specify that a configuration bean will be included if a specified class is present using the @ConditionalOnClass annotation, or if a class is absent using the @ConditionalOnMissingClass annotation.

Let’s specify that our MySQLConfiguration will only be loaded if the class DataSource is present,¬†in which case we can assume the application will use a database:

public class MySQLAutoconfiguration {
3.2. Bean Conditions

If we want to include a bean only if a specified bean is present or not, we can use the @ConditionalOnBean and @ConditionalOnMissingBean annotations.

To exemplify this, let’s add an entityManagerFactory bean to our configuration class, and specify we only want this bean to be created if a bean called dataSource is present and if a bean called entityManagerFactory is not already defined:

@ConditionalOnBean(name = "dataSource")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean em
      = new LocalContainerEntityManagerFactoryBean();
    em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    if (additionalProperties() != null) {
    return em;

Let’s also configure a transactionManager bean that will only be loaded if a bean of type JpaTransactionManager is not already defined:

@ConditionalOnMissingBean(type = "JpaTransactionManager")
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    return transactionManager;
3.3. Property Conditions

The @ConditionalOnProperty annotation is used to specify if a configuration will be loaded based on the presence and value of a Spring Environment property.

First, let’s add a property source file for our configuration that will determine where the properties will be read from:

public class MySQLAutoconfiguration {

We can configure the main DataSource bean that will be used to create connections to the database in such a way that it will only be loaded if a property called usemysql is present.

We can use the attribute havingValue to specify certain values of the usemysql property that have to be matched.

Let’s define the dataSource bean with default values that connect to a local database called myDb if the usemysql property is set to local:

  name = "usemysql", 
  havingValue = "local")
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();

    return dataSource;

If the usemysql property is set to custom, the dataSource bean will be configured using custom properties values for the database URL, user, and password:

@Bean(name = "dataSource")
  name = "usemysql", 
  havingValue = "custom")
public DataSource dataSource2() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setUsername(env.getProperty("mysql.user") != null 
      ? env.getProperty("mysql.user") : "");
    dataSource.setPassword(env.getProperty("mysql.pass") != null 
      ? env.getProperty("mysql.pass") : "");
    return dataSource;

The file will contain the usemysql property:


If an application that uses the MySQLAutoconfiguration wishes to override the default properties, all it needs to do is add different values for the mysql.url, mysql.user and mysql.pass properties and the usemysql=custom line in the file.

3.4. Resource Conditions

Adding the @ConditionalOnResource annotation means that the configuration will only be loaded when a specified resource is present.

Let’s define a method called additionalProperties() that will return a Properties object containing Hibernate-specific properties to be used by the entityManagerFactory bean, only if the resource file is present:

  resources = "")
Properties additionalProperties() {
    Properties hibernateProperties = new Properties();

      env.getProperty("mysql-hibernate.show_sql") != null 
      ? env.getProperty("mysql-hibernate.show_sql") : "false");
    return hibernateProperties;

We can add the Hibernate specific properties to the file:

3.5. Custom Conditions

If we don’t want to use any of the conditions available in Spring Boot, we can also define custom conditions by extending the SpringBootCondition class and overriding the getMatchOutcome() method.

Let’s create a condition called HibernateCondition for our additionalProperties() method that will verify whether a HibernateEntityManager class is present on the classpath:

static class HibernateCondition extends SpringBootCondition {

    private static String[] CLASS_NAMES
      = { "org.hibernate.ejb.HibernateEntityManager", 
          "org.hibernate.jpa.HibernateEntityManager" };

    public ConditionOutcome getMatchOutcome(ConditionContext context, 
      AnnotatedTypeMetadata metadata) {
        ConditionMessage.Builder message
          = ConditionMessage.forCondition("Hibernate");
          .filter(className -> ClassUtils.isPresent(className, context.getClassLoader()))
          .map(className -> ConditionOutcome
            .items(Style.NORMAL, className)))
          .orElseGet(() -> ConditionOutcome
            .noMatch(message.didNotFind("class", "classes")
            .items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));

Then we can add the condition to the additionalProperties() method:

Properties additionalProperties() {
3.6. Application Conditions

We can also specify that the configuration can be loaded only inside/outside a web context, by adding the @ConditionalOnWebApplication or @ConditionalOnNotWebApplication annotation.

4. Testing the Auto-Configuration

Let’s create a very simple example to test our auto-configuration. We will create an entity class called MyUser, and a MyUserRepository interface using Spring Data:

public class MyUser {
    private String email;

    // standard constructor, getters, setters
public interface MyUserRepository 
  extends JpaRepository<MyUser, String> { }

To enable auto-configuration, we can use one of the @SpringBootApplication or @EnableAutoConfiguration annotations:

public class AutoconfigurationApplication {
    public static void main(String[] args) {, args);

Next, let’s write a JUnit test that saves a MyUser entity:

  classes = AutoconfigurationApplication.class)
  basePackages = { "com.baeldung.autoconfiguration.example" })
public class AutoconfigurationTest {

    private MyUserRepository userRepository;

    public void whenSaveUser_thenOk() {
        MyUser user = new MyUser("");;

Since we have not defined our DataSource configuration, the application will use the auto-configuration we have created to connect to a MySQL database called myDb.

The connection string contains the createDatabaseIfNotExist=true property, so the database does not need to exist. However, the user mysqluser or the one specified through the mysql.user property if it is present, needs to be created.

We can check the application log to see that the MySQL data source is being used:

web - 2017-04-12 00:01:33,956 [main] INFO  o.s.j.d.DriverManagerDataSource - Loaded JDBC driver: com.mysql.cj.jdbc.Driver
5. Disabling Auto-Configuration Classes

If we wanted to exclude the auto-configuration from being loaded, we could add the @EnableAutoConfiguration annotation with exclude or excludeName attribute to a configuration class:

public class AutoconfigurationApplication {

Another option to disable specific auto-configurations is by setting the spring.autoconfigure.exclude property:

6. Conclusions

In this tutorial, we’ve shown how to create a custom Spring Boot auto-configuration. The full source code of the example can be found over on GitHub.

The JUnit test can be run using the autoconfiguration profile: mvn clean install -Pautoconfiguration.

Categories: Blogs

3 Steps to Writing and Reading XML Files

To read or write XML files, you should consider JAXB (Java Architecture for XML Binding). JAXB will convert and reconvert XML objects using marshalling (writing to XML) and unmarshalling processes.

When and Where Do I Need to Write XML Files? Creating a Custom Configuration or UI File

Suppose, in a project, you need to customize the User Data for each field or configure the system’s database to your standard.

Categories: Communities

Building Java (and Android) Apps on the Blockchain [Slideshow]

I gave a tech talk at Pivotal Labs today on developing Java applications on the Ethereum blockchain.

The slides are available below.

Categories: Communities

Software Adoption Surveys: From Quantity To Quality!

In a democracy, everyone is equal. One person, one vote, and all votes are equal since all people are equal.

Erroneously, that approach is applied to software adoption surveys too. Anyone at all can respond to a survey and can indicate that they use software product X, Y, or Z. However, what if I am a student paddling in the shallow waters of software development, with the likelihood that I'll abandon it before I graduate, while you are a senior Java architect creating mission critical software for NASA? Should my vote for product X, Y, or Z be equal to yours? Surely not?

According to "Baeldung", NetBeans usage has MORE THAN DOUBLED between 2016 and 2017, from 5.9% to 12.4%:

And look here! NetBeans IDE is 2nd, beating IntelliJ IDEA and Eclipse:

And... wow... look at this one, NetBeans is 2nd, after Eclipse, leaving IntelliJ IDEA far away in the dust:

Hurray, NetBeans is waaaaay more popular than X, Y, and Z! 

Sorry, the above results are meaningless, just like the results by RedMonk and the results by RebelLabs. Yes, even though the above results favor NetBeans, the tool that I like and have been promoting, and will continue to promote, for many years, the above results are bullshit.

When you look at the results of a software adoption survey, you have no idea at all whether the 70% using product A are creating financial software while the 2% using product B are brain surgeons or rocket scientists. And surely that makes a difference, i.e., knowing that information makes a difference in how you would evaluate software adoption surveys. Your software may be aimed at brain surgeons or rocket scientists and so the 70% doing financial software with a competing product are irrelevant to you.

So, let's stop the meaninglessness of software adoption surveys. Let's instead turn things around and do surveys of projects instead of people. One project, one vote‚ÄĒinstead of one person one vote.

And there'd also need to be distinctions between types of projects. Plus, there'd need to be agreement on which specific projects to survey, with the same survey being done with exactly the same projects over a specific number of years, e.g., 5, to show trends.

We'd get richly textured results like this:

  • In the 1000 commercial projects surveyed over the past 5 years, 40% use Java-based product X, 30% use competing Java-based product Y, while the remainder don't use Java-based products at all. Over the past 3 years, adoption has shifted significantly amongst the 1000 commercial projects surveyed, from product B to product A in the financial sector, while in the logistics sector adoption has remained constant. Meanwhile, Java-based product Z has declined, though not significantly, and remains popular in large enterprises with over 500 fulltime software developers who combine product A with product B.

  • 90% of the 700 financial projects that have been surveyed use product X, while 75% of the 500 scientific projects that have been surveyed use product X together with competing product Y because product Y provides benefit A in the context of process B which is important specifically to scientific projects because of reason C. In 20% of the organizations surveyed, strict rules are defined about software usage, while 70% leave it up to the developer, and 10% did not respond to this question. 

  • In all of the 2500 organizations with over 100 fulltime developers surveyed, three competing open source products are used in one way or another. In the aerospace domain, which is 15% of the 2500 organizations surveyed, product A is slightly more popular than product B, while in the educational domain, which is 60% of the 2500 organizations surveyed, product B is clearly dominant, while product C is mainly popular amongst developers at startups, encompassing 20% of the organizations surveyed.  

Wouldn't these kinds of results be far more meaningful than the winner-take-all mentality of one (random) person, one vote‚ÄĒwhich is the current approach that software adoption surveys take? You'd be able to judge the relevance of the results based on your target audience. For example, you'd be able to say things like: "Well, since we don't care about startups, it doesn't matter that we're not popular there." Right now, we're unable to say these kinds of meaningful things because of the random 2000 people taking part in your survey, they could all be in the same country or working in a similar domain or a majority could be sympathetic to your organization, or came across your survey because they happened to be following you on Twitter, or all working on the same or similar projects.  

Let's stop focusing on the very simplistic "how many people filled in my survey" (e.g, "Last year, 2250 Java developers decided to take the time to answer the questions, and so it's fantastic to see this year that number is almost double - we got 4439 answers.") and switch over to the much more complicated task of "how can I be sure I am getting quality data from my survey". E.g., if you were to ask me "do you use OpenOffice or Microsoft Word", I would probably say "OpenOffice" even though I am using both these products more or less equally (together with other small editors like Notepad and Sublime, but you'll never know that since you never asked about that), though you're not giving me the choice to say that, and my individual usage statistic is meaningless if everyone else answering your survey is just like me or working on the same project or I have persuaded my friends to fill in your meaningless survey or rocket scientists at NASA don't care enough or are behind a firewall and so aren't filling in your survey.

To be honest, I am not hopeful, at all. I admit to being a bit cynical since I have the feeling that the most important reason for software surveys is not to gain meaningful insights, though I believe you completely when you claim good intentions and I applaud you for what I think you think you're honestly trying to do‚ÄĒinstead, the reason why surveys exist is to promote the organization behind the survey as a neutral repository of truth and insight. And the glossier the brochures you print, the shinier the graphs that display your random data, the more suspicious I am that you're marketing your organization rather than gathering meaningful data.
Categories: Open Source