Feed aggregator

Java Platform and Java Community Process Overview

Javalobby Syndicated Feed - Mon, 03-Apr-17 21:01

In this article, I'm going to explain the most important pieces of the Java platform and provide a brief explanation of the process responsible for evolving it. First I'm going to introduce the different Java editions—Java MEJava SE and Java EE—and some important acronyms related to them, like JDKJREJVMJSPJPA, etc. In the end, I will provide an overview of the Java Community Process (JCP).

Java Editions

Before diving into the Java Community Process (JCP), it's important to understand the main pieces of the platform. Java is distributed in three different editions: Java Standard Edition (Java SE), Java Enterprise Edition (Java EE) and Java Micro Edition (Java ME).

Categories: Java

Spring Data With JPA and @NamedQueries

Javalobby Syndicated Feed - Mon, 03-Apr-17 13:01

If you use Spring Data and @NamedQuery annotations for your JPA entities, you can easily use them in a more convenient way with the Spring Data repository.

In a previous article, we created a Spring Data project using Spring Boot and Docker. We will use pretty much the same project and enhance our repository’s functionality.

Categories: Java

Project Amber: Smaller, Productivity-Oriented Java Language Features

Javalobby Syndicated Feed - Mon, 03-Apr-17 09:01

Brian Goetz's recent message Welcome to Amber! introduces Project Amber (part of OpenJDK and proposed originally in January). Goetz opens the message with the introduction, "Welcome to Project Amber, our incubation ground for selected productivity-oriented Java language JEPs." Goetz reiterates that Project Amber is not for discussing ideas for arbitrary potential new language features, but rather is for collecting new language features for which a JDK Enhancement Proposal (JEP) already exists ("let's keep the focus on the specific features that have been adopted").

Three JEPs are already associated with Project Amber:

Categories: Java

CRUD operations on Spring REST resources with Kotlin

codecentric Blog - Mon, 03-Apr-17 05:56

In this practical, hands-on post I would like to share some of my experience in building REST services wih JSON and Spring(Boot) using Kotlin. All examples can be transferred to Java, and if you use the indispensable Lombok library it doesn’t even look that ugly.
Today I will concentrate on the mother of all REST use cases: a simple CRUD (create/read/update/delete) api, implemented as a SpringBoot application in Kotlin. You can get the source code here:

git clone git@gitlab.com:jsprengers/spring-rest-kotlin-tips.git

A word of warning: REST is often mistakenly referred to as a protocol. REST is an architectural style that, unlike SOAP, is much more free-format, which is a blessing as well as a curse.
Our application offers all four CRUD operations using the respective http verbs POST,GET,PUT,DELETE. A GET request retrieves either a single entity (http://localhost:8080/customers/123), or the entire list: http://localhost:8080/customers>. The latter ‘get-all’ method typically supports filtering the list in the request parameter, e.g. ?age=20, although not in this present example.
Let’s assume that we want to store a user’s name (mandatory) and date of birth (optional) in our database. For this example we use a simple hashmap in-memory storage.

data class CustomerEntity(
    var id: Long? = null, 
    var name: String, 
    var dateOfBirth: LocalDate?)

Since the mandatory numeric ID is auto-assigned (with the aid of annotations in a real production system) by the persistence implementation after constructing the entity, you must type it as a nullable Long?, because for a very brief moment it will be null. Entity classes should never be exposed through your public REST endpoints, especially not when they contain JPA or (worse) Hibernate annotations, because that would require client code to have a compilation dependency on these persistence libraries. The REST endpoint must expose data transfer objects (DTOs) of our customers, which ideally reside in a separate api deliverable. Consumers of our service can then import this api jar.
Don’t be discouraged that you have to make a DTO class separate from the entity class. With a tailor-made DTO you can supply derived properties that are not in the database. Imagine that the consumer of our service is not interested in the exact date of birth but only the customer’s current age. The DTO returned from the service will look like this:

data class CustomerDTO(val id: Long, val name: String, val age: Int?)

and the serialized response would be:

    "id": 4,
    "name": "Jasper Sprengers",
    "age": 47

Web resources in REST are not persistent entities. We’re not obliged to create a one-to-one mapping between database tables and DTO classes. Our customer resource is a uniquely identifiable entity backed by a database entry, but its properties/fields may be partly derived. You could for example have fields for gender and preferred language in the entity and a localized salutation field in your DTO. Note that the id property is a proper Long field, and not a Long?. Since the entities are retrieved from storage, the ID is guaranteed to be non-null.
The REST endpoint looks like this:

class CustomerEndpoint @Autowired constructor(private val repository: CustomerRepository) {

    @RequestMapping(method = arrayOf(RequestMethod.GET))
    fun getAllCustomers(): List {
        return repository.getAll()

    @RequestMapping(value = "{id}", method = arrayOf(RequestMethod.GET))
    fun getCustomerById(@PathVariable("id") id: Long): CustomerDTO {
        return repository.getById(id)

This is all well and good, but we still haven’t POST-ed anything to our repository. How about this?

@RequestMapping(method = arrayOf(RequestMethod.POST))
 fun createCustomer(@RequestBody createRequest: CustomerDTO): CustomerDTO {
     return repository.save(createRequest)

No, that won’t work. The CustomerDTO class is read-only. The database expects a precise date of birth instead of an age and it doesn’t want a unique id from you. Better to create a custom DTO class specially catered for customer creation requests.

data class CreateCustomerDTO(val name: String, val dateOfBirth: LocalDate? = null)

This contains everything the storage requires. You can even leave the date of birth blank:


The endpoint method looks like this:

@RequestMapping(method = arrayOf(RequestMethod.POST))
  fun createCustomer(@RequestBody createRequest: CreateCustomerDTO): CustomerDTO {
      return repository.save(createRequest)

Deleting from a resource is easy. Since that requires only the correlating entity’s unique id, the canonical format is:

@RequestMapping(value = "{id}", method = arrayOf(RequestMethod.DELETE))
   fun deleteCustomerById(@PathVariable("id") id: Long): CustomerDTO {
       return repository.removeById(id)

With creation and retrieval covered, let’s move on to PUT requests for updating. Updating a persisted entity requires at least a valid ID and the new values for the database fields we want to update. CustomerDTO has this non-null id field, but it doesn’t have the dateOfBirth, only the derived age field. Fine, then we’ll just create an exact copy of the entity with a non-null id field. Not so great either: now you must provide all of the customer’s values in the PUT request, even the ones that don’t need updating. From a transactional, multi-user point of view it is safer to update only those fields that need updating. That way Alice and Bob can simulaneously update different properties in Eve’s data without conflicts. Break out of the RDBMS mindset and don’t treat a PUT request as an instruction to overwrite row 42 in the CUSTOMER table with the following values. Rather, treat the payload of the PUT request as an instruction to alter one or more properties of an entity. Can we do that with our existing DTOs? If we were dealing with only non-nullable properties, then this would be a workable solution:

data class UpdateCustomerDTO(val id: Long, val name: String?, val dateOfBirth: LocalDate?)

Any property that has a null value in the DTO should be ignored for the update. So to update a customer’s name we PUT:

  "id": 8,
  "name": "Aristotle the wise"

And our code for updating would look like this:

fun save(updateRequest: UpdateCustomerDTO): CustomerDTO {
        val entity: CustomerEntity = getEntityFromStorage(updateRequest.id)
        if (updateRequest.name != null)
            entity.name = updateRequest.name
        //same drill for all the other fields      

However, our CustomerEntity contains a date of birth field which can be populated or nullified at will during the entity’s lifetime. With the above solution you cannot express that difference. Whereas Javascript and Typescript can distinguish between undefined and null object properties, strongly typed Kotlin and Java cannot. We need some means to express the three options of non-null (overwrite), null (set to null) and undefined (ignore for update). At first I thought of putting the updatable field in an optional list. Use a list of one for non-null elements, an empty list to set the value to null and leave the field out or null to ignore it.

  "id": 8,
  "name": ["Aristotle the wise"]
  "dateOfBirth": null

It’s easy to implement in JavaScript client code, but it just feels wrong. Better to create an additional generic wrapper, like so:

data class UpdateField(val value: T? = null, val ignored: Boolean = false) {

    fun get(): T = value ?: throw IllegalStateException("value cannot be null.")
    fun getOrNull(): T? = value

    companion object {
        fun  ignore() = UpdateField(ignored = true)
        fun  setNull() = UpdateField()
        fun  of(value: T) = UpdateField(value = value)

Have a look at the IntegrationTest for usage of the factory methods in the companion object. Yes, it’s a bit of extra code, but it’s highly generic, hence re-usable. Since the Kotlin source code is so compact and the classes highly related I like to put all three flavours in the same Customer.kt source file

data class CustomerDTO(val id: Long, val name: String, val age: Int?)
data class CreateCustomerDTO(val name: String, val dateOfBirth: LocalDate? = null)
data class UpdateCustomerDTO(val id: Long,
                             val name: UpdateField = UpdateField.ignore(),
                             val dateOfBirth: UpdateField = UpdateField.ignore())

Now to update a specific field to a new value, the JSON looks like:

"name":{"value": "Aristotle the wise", "ignored": false},
"dateOfBirth":{"value": null, "ignored": true}

I agree that’s pretty verbose. Luckily the ignored property is false by default in the UpdateField, so you can leave it out. Any UpdateCustomer field not present in the JSON is populated with a default ‘ignore’ object, so this is equivalent to the previous JSON snippet:

"name":{"value": "Aristotle the wise"}

The value field is null by default, so here’s how you set a nullable field to null:


This however will cause an error:


Because name is a non nullable field. The actual save method in our simple hashmap-backed repository looks like this:

 fun save(customerUpdate: UpdateCustomerDTO): CustomerDTO {
        val entity: CustomerEntity = cache[customerUpdate.id] ?: throw IllegalArgumentException("No customer with id ${customerUpdate.id}")
        if (!customerUpdate.name.ignored)
            entity.name = customerUpdate.name.get()
        if (!customerUpdate.dateOfBirth.ignored)
            entity.dateOfBirth = customerUpdate.dateOfBirth.getOrNull()
        cache.put(customerUpdate.id, entity)
        return createDTO(entity)

And of course if a persistent field for some reason is never eligible for updating, then don’t include it in the update dto. A final technical caveat when using Kotlin single-constructor data classes with jackson serialization: you must import the jackson-module-kotlin> module and register the KotlinModule for it to work properly. Read more.
I hope these examples can help you to make your existing REST implementations more flexible and user-friendly. If I have somehow managed to win you over to the Kotlin camp, then so much the better. If not, I’ll be back in a couple of weeks.

The post CRUD operations on Spring REST resources with Kotlin appeared first on codecentric AG Blog.

Categories: Agile, Java, TDD & BDD

Using Apache POI to Read Excel

Javalobby Syndicated Feed - Mon, 03-Apr-17 03:01

Apache POI is a Java library to read and write Microsoft Documents including Word and Excel. Java Excel API can read and write Excel 97-2003 XLS files and also Excel 2007+ XLSX files. In this article, we show how to get going using the Apache POI library to work with Excel files.

Maven Dependency

You need the following maven dependency to work with Apache POI.

Categories: Java

java.lang.reflect.TypeVariable getBounds Is Not Thread Safe

Javalobby Syndicated Feed - Mon, 03-Apr-17 00:01

java.lang.reflect.TypeVariable getBounds is not thread safe. Calling it from multiple threads might even crash your JVM.

The following method shows you the use of getBounds(). The method getBounds is used to get the upper bound(s) of a generic type:

Categories: Java

How Java’s Built-In Garbage Collection Will Make Your Life Better (Most of the Time)

Javalobby Syndicated Feed - Sun, 02-Apr-17 21:01

“No provision need be made for the user to program the return of registers to the free-storage list.”

This line (along with the dozen or so that followed it) is buried in the middle of John McCarthy’s landmark paper, “Recursive Functions of Symbolic Expressions and Their Computation by Machine,” published in 1960. It is the first known description of automated memory management.

Categories: Java

A Guide to Java's SimpleDateFormat

Javalobby Syndicated Feed - Sat, 01-Apr-17 22:01

We can easily parse and format dates in Java with the SimpleDateFormat class. It is similar to using the POSIX function strftime() in C/C++ with a few gotchas. Let's learn the proper usage of SimpleDateFormat and delve into some of its issues.

Parsing Dates with SimpleDateFormat

Create a SimpleDateFormat instance by specifying the format. (See the table farther down in the article for all format directives.)

Categories: Java

Spring Tips: The Spring Framework *Utils Classes [Video]

Javalobby Syndicated Feed - Fri, 31-Mar-17 21:01

Hi, Spring fans! In this installment, we’ll look at some of the many *Util classes in the Spring framework. These utility classes are already there and can be a major time-saver, if you know where to look!

Categories: Java

Constructor Chaining in Java

Javalobby Syndicated Feed - Fri, 31-Mar-17 13:01

Constructors are one of the simplest, yet trickiest object creation concepts in Java. A lot of experienced Java developers get confused about it. A source of confusion is relating it to methods, which is a totally different concept. One of the key differences between a method and a constructor is that constructors don't return anything. A lot of things happen under the hood when you invoke a constructor.

How Does Constructor Chaining Work?

When you invoke a constructor from another constructor, it's called constructor chaining. Whether you're dealing with a standalone constructor or a parent class' constructor, the end of the chain will always be the Object's class constructor because every class is inherited from the Object class by default.

Categories: Java

This Week in Spring: Reactor in Kotlin, Spring Boot, and REST Docs

Javalobby Syndicated Feed - Fri, 31-Mar-17 09:01

Welcome to another installment of This Week in Spring! This week I’m in Omaha, Nebraska, speaking to customers and tonight I’ll be presenting at an event co-sponsored by the Omaha, JUG and the local Omaha, Spring Users Group, talking about reactive Spring. Don’t be shy, come out and say hi!

Categories: Java

Enhance Wicket With Spring Boot

Javalobby Syndicated Feed - Fri, 31-Mar-17 03:01

Wicket has traditionally provided a solid integration with the core part of Spring (i.e. the container) with its dedicated module wicket-spring. Recently, a new independent project called wicket-spring-boot has extended Spring integration to Spring Boot, too. With it, we can use Spring Boot as application starter and take advantage of its autoconfigure capabilities to set up the entire application.

To run a Wicket application with Spring Boot, we must first include the following dependency (for Maven) in our project:

Categories: Java

Aggregate Pattern

Javalobby Syndicated Feed - Fri, 31-Mar-17 00:01

I’ve recently done some reading on DDD and Aggregates in particular. Since many people struggle to understand the pattern, I decided to try to explain it myself.


Imagine that you’re writing yet another e-commerce application and you’re tasked with writing the all-important Order class:

Categories: Java

Java vs. Python: Which One Is Best for You?

Javalobby Syndicated Feed - Thu, 30-Mar-17 21:01

Few questions in software development are more divisive or tribal than choice of programming language. Software developers often identify strongly with their tools of choice, freely mixing objective facts with subjective preference.

The last decade, however, has seen an explosion both in the number of languages used in production and the number of languages an individual developer is likely to employ day to day. That means that language affiliations are sometimes spread more loosely and broadly across different codebases, frameworks, and platforms. Modern projects and modern developers are increasingly polyglot—able to draw on more languages and libraries than ever before. Informed choice still has a part to play.

Categories: Java

Is the JVM the Most Important Element of the Java Ecosystem?

Javalobby Syndicated Feed - Thu, 30-Mar-17 13:01

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 do you consider to be the most important elements of the Java ecosystem?" Here's what they told us:

  • The JVM is critical and will outlive the language. Now using Scala, Closure, Kotlin, and Groovy as a dynamic language. The JVM is a powerful concept that will outlive the language itself. It’s interoperable with other languages. It takes time to reach the level of maturity it has.
  • The JVM is rock solid and proven stable. Nothing compares. Look at the landscape of specifications. Everything under Java SC, EE, Ecosystem, OSGi, as Oasys serve as backs for the industry to build from. The ecosystem that the JVM and specifications have brought on is astounding. Massive resources are available. There is no problem that hasn’t been addressed by Java. No significant new developing to be done. So many solutions available.
  • The Spring framework for building out frameworks in Java. It’s becoming the defacto standard along with IBM, Red Hat JBoss. People are moving away from enterprise java beans to Spring.
  • Open source projects under the Eclipse umbrella. We track the new potential uses of the product. We track Apache projects as they are very interesting and we can provide unique solutions to problems.
  • The core strength is the JVM. It’s the most stable part of the platform and serves as the core of a lot of cool things like scaling, performance, and concurrence. There is huge breadth and depth on top (e.g., JGroovy) that’s important for the ecosystem to flourish. Some problems have been solved like just-in-time compilation. Longevity is a testament to its usefulness.
  • Write once run anywhere.
  • It’s the story of enterprise web development with ASP .Net second and everything else far behind. Organizations like the Apache Foundation and others built out the scaffolding to build on top of so you don’t have to build your own infrastructure.
  • Java 8 is more efficient and more powerful, easier to write less code. It also introduced lambda. It's great for web and mobile devices.
  • 1) Formal package management is compared to others and dependency management. They’ve thought about their JVM for a long time. It’s easier than other languages. 2) Robustness of the ecosystem which already exists. 3) Available talent pool. Taught in schools and used across stacks.

What's the most important element of the Java ecosystem from your perspective? And in case you're wondering, here's who we talked to:

Categories: Java

Spring Data Improvements in IntelliJ IDEA 2017.1

Javalobby Syndicated Feed - Thu, 30-Mar-17 09:01

The upcoming IntelliJ IDEA 2017.1 includes numerous features to help Spring developers. In this post, we’re going to look specifically at the feature for Spring Data. Support for Spring Data has been updated to include support for features in release train Kay.

Navigation for New Repository Types

We’ve added a gutter icon for navigation to declarations of specific repository types

Categories: Java

Testing DTOs and REST Controllers in Spring Boot

Javalobby Syndicated Feed - Thu, 30-Mar-17 09:00

In this post, I will cover some tests that can be run to ensure that your DTOs (Data Transfer Objects) are being serialized and deserialized correctly, leading onto testing whether they are being passed to and returned from a REST Controller without errors.

Have a look at my previous posts Passing Data Transfer Objects with GET in Spring Boot and Returning Data Transfer Objects from a Rest Controller in Spring Boot for information about how the DTOs are passed to and returned from the REST Controller. Also have a look at Spring’s starter guide if you're starting from scratch. The setup, which is not described in this post, is covered there. 

Categories: Java

Ratpacked: Using Spring Cloud Contract

Javalobby Syndicated Feed - Thu, 30-Mar-17 03:01

Spring Cloud Contract is a project that allows you to write a contract for a service using a Groovy DSL. In the contract, we describe the expected requests and responses for the service. From this contract, a stub is generated that can be used by a client application to test the code that invokes the service. Spring Cloud Contract also generates tests based on the contract for the service implementation. Let's see how we can use the generated tests for the service implementation for a Ratpack application.

Spring Cloud Contract comes with a Gradle plugin. This plugin adds the task generateContractTests, which creates tests based on the contract we write. There are also tasks to create the stub for a client application, but here we focus on the server implementation. In the following Gradle build file for our Ratpack application, we use the Spring Cloud Contract Gradle plugin. We configure the plugin to use Spock as the framework for the generated tests.

Categories: Java

Introduction to Spring Boot REST Services

Javalobby Syndicated Feed - Thu, 30-Mar-17 00:01
“The only true wisdom is in knowing you know nothing.”
― Socrates

Getting started with Spring and Spring Boot? Welcome!

This is a beginner level tutorial for implementing a Hello World REST Service using Spring Boot. The emphasis is on getting the basic application outline worked out — one to which we can add various enterprise features in further articles.

Categories: Java

Using Groovy to Quickly Analyze Terracotta Health Check Properties

Javalobby Syndicated Feed - Wed, 29-Mar-17 21:01

One of the considerations when configuring Terracotta servers with tc-config.xml is the specification of health check properties between Terracotta servers (L2-L2), from clients to server (L1-L2), and from server to client (L2-L1). Terracotta checks the combination of these properties' configurations in high-availability scenarios to ensure that these combinations fall in certain ranges. This blog post demonstrates using Groovy to parse and analyze a given tc-config.xml file to determine whether Terracotta will provide a WARN-level message regarding these properties' configurations.

The "About HealthChecker" section of the Terracotta 4.3.2 BigMemory Max High-Availability Guide (PDF) describes the purpose of the HealthChecker: "HealthChecker is a connection monitor similar to TCP keep-alive. HealthChecker functions between Terracotta server instances (in High Availability environments), and between Terracotta sever instances and clients. Using HealthChecker, Terracotta nodes can determine if peer nodes are reachable, up, or in a GC operation. If a peer node is unreachable or down, a Terracotta node using HealthChecker can take corrective action."

Categories: Java

Thread Slivers eBook at Amazon

Syndicate content