Feed aggregator

Refactoring to Functional Patterns in Scala

Javalobby Syndicated Feed - Wed, 22-Nov-17 22:01

If you have a background in Java like me, you've probably read Refactoring To Patterns. It's a very cool book about refactoring that shows you how to refactor Object Orientated code step by step and eventually reach full-blown Gang of Four design patterns. It had a huge impact on me at the time. It left me with the feeling that code is alive and wants to be rearranged this way, and that patterns emerge naturally.

Fast forward 10 years, and I work at a very cool startup (Bigpanda) where we use Scala and functional programming for our back-end services. Working with FP is very different, and in my opinion, far easier. There are no more complicated class hierarchies and no more complicated patterns, only functions, functions, functions. If GoF design patterns are no longer our destination, then the refactoring steps we must take are very different.

Categories: Java

How to Transpose a Collection in Scala [Snippets]

Javalobby Syndicated Feed - Wed, 22-Nov-17 14:01


You want to transpose a Map of Lists to a List of maps.


def main(args: Array[String]) {
    val m = Map(
        "breakfast" -> List("cereals", "omelet", "fruits"),
        "lunch" -> List("sandwich", "salad", "steak"),
        "dinner" -> List("pasta", "taco", "soup"))
    val dietList = m.map {
        case (k, vs) =>
            vs.map(k -> _)

Categories: Java

This Week in Spring: Spring Cloud and Microservices

Javalobby Syndicated Feed - Wed, 22-Nov-17 10:01

Hi, Spring fans! Welcome to another installment of This Week in Spring! Can you believe we’re less than six weeks away from 2018? Time sure flies when you’re having fun!

This week I’m in Los Angeles talking to community members and then taking in the Thanksgiving holiday here in the US surrounded by friends and family. Thanksgiving is a chance to reflect on that for which we are thankful. I am sure that I speak for all of us here on the Spring and Pivotal teams when I say that we are thankful for you. Thank you for making this the most amazing, dynamic, exhilarating and interesting community in tech. If you’re in the US, happy Thanksgiving! Either way, we’ve got a lot to cover this week so let’s get to it.

Categories: Java

Transforming Either[Future[A],Future[B]] to Future[Either[A,B]]

Javalobby Syndicated Feed - Wed, 22-Nov-17 04:01

Recently, I came across one weird situation in which I was getting a Future[Either[String , Future[A]]]. It was getting more and more complex, so I thought about taking out the Future from the Either and then flattening it out, as most of us do anyway. 

But this time, this simple trick was not working, which led to me getting frustrated. Then, while searching for a solution, I came across a very good library for Scala known as Cats, which seemed to solve my problem.

Categories: Java

Dynamic Validation with Spring Boot Validation

codecentric Blog - Wed, 22-Nov-17 01:30

Serverside validation is not only a way to prevent eventual attacks on a system, it also helps ensure data quality. In the Java environment JSR 303 Bean Validation and the javax.validation packages provide developers with a standardized way of doing so. Fields that have to fulfill certain criteria receive the corresponding annotations, e.g. @NotNull, and these are then evaluated by the framework. Naturally, for checking more specific conditions, there is the possibility of creating custom annotations and validators.

The Spring framework has a good Bean Validation integration. It is e.g. possible to validate an incoming request inside a RestController by adding the @Valid annotation to the request parameter. This ensures that the incoming object is validated. A simple example is the following controller:

public class DataController {
    @RequestMapping(value = "/input", method = RequestMethod.POST)
    public ResponseEntity<?>; acceptInput(@Valid @RequestBody Data data ) {
        return new ResponseEntity<>(HttpStatus.OK);

When entering the method, the very generic “Data” object has already been completely validated. If a field inside it wasn’t valid, the client would receive a 4xx status code.

Still, there is one disadvantage when using the validations: the annotations are completely static. It is not possible to read information e.g. from the request. Nevertheless, there are ways and means to overcome this limitation and enrich one’s own application with more dynamic validations. To be more specific, we want to extract one or more values from the incoming HttpRequest and vary the validation depending on the values.

More dynamic validation

Not so long ago, a joke went around regarding a famous social media platform’s charater limit. This picture provides a very nice summary.

Our example application shall be based on this use case. When our application receives a request that has the language de-DE set in its header, the text inside the JSON payload is allowed to be 280 characters long. For every other language we enforce a limit of 140 characters. In order to demonstrate the combination with static validation, the DTO contains a number field, which is being validated, too. More precisely, the object looks like this:

public class Data {
    private final String someStringValue;
    private final int someIntValue;

    public Data(@JsonProperty("someStringValue") String someStringValue, @JsonProperty("someIntValue") int someIntValue) {
        this.someStringValue = someStringValue;
        this.someIntValue = someIntValue;

    public String getSomeStringValue() {
        return someStringValue;

    public int getSomeIntValue() {
        return someIntValue;

The JSON annotations come from Jackson and are already included in Spring Boot Starter Web, which is quite practical for our example. The someStringValue, which already has an annotation, shall be the field we use for checking the character limit.

For the validation we need a custom class containing the logic:

public class StringValueValidator {

    public void validate(String language, Data data, Errors errors) {
        if (!"de-DE".equals(language)) {
            if (data.getSomeStringValue().length() > 140) {

I would like to emphasize here that the validator class does not implement any javax.validation interface, not even javax.xml.validation.Validator. This is because the validation depends on values from the request and is supposed to take place after the rest of the validation. Still, we want to utilize the existing checks (@NotNull und @Min). Except for the @Component annotation, the StringValueValidator is a POJO.

The Errors object originates from Spring and has the fully qualified name org.springframework.validation.Errors. As you can see, in case of a negative test result, we add the field that is being rejected to the Errors. It is also possible to add a more specific error message there.

Only using the @Valid annotation in the controller is not sufficient anymore. The existing errors are also needed as an additional parameter. By adding Errors to the parameter list, Spring recognizes that it should not reject the request immediately and pass the existing validation errors into the method. We have to be careful here because Spring will no longer send an automatic 4xx response in case of validation errors for us. We are now responsible ourselves to return the appropriate status code.

Next to the errors, we let Spring extract the language from the header. Of course, we could access the HttpRequest here but that way we save some effort. The language, the data, and the existing errors are then passed to our StringValueValidator. The complete request method looks like this:

    @RequestMapping(value = "/validation", method = RequestMethod.POST)
    public ResponseEntity<?> acceptData(@Valid @RequestBody Data data, Errors errors, 
        @RequestHeader(HttpHeaders.ACCEPT_LANGUAGE) String language) {
        stringValueValidator.validate(language, data, errors);
        if (errors.hasErrors()) {
            return new ResponseEntity<>(createErrorString(errors), HttpStatus.BAD_REQUEST);
        return new ResponseEntity<>(HttpStatus.OK);

We now have a dynamic validation, adapting its behaviour with respect to the request. The language shall only serve as an example placeholder for any value that could be inside the request. Alternatives could be the request URL or values inside the payload.

One of the curious things here is that one would expect to be able to make the validator a RequestScoped bean and then have it injected in the controller. Unfortunately, it was not possible for me to get this approach running. When testing with more than one request, the first one always got “stuck” inside the validator and the test then failed.

You can find the complete example project includung unit tests on GitHub: https://github.com/rbraeunlich/spring-boot-additional-validation


As shown, it is possible to extend the validation of fields with dynamic aspects in a quite simple way. We were even able to combine our extended validation with the existing one without experiencing any constraints. Especially complex validations that cannot be represented by pure annotations can easily be added to a RestController in this way.

The post Dynamic Validation with Spring Boot Validation appeared first on codecentric AG Blog.

Categories: Agile, Java, TDD & BDD

10 Java Experts and Devs to Follow

Javalobby Syndicated Feed - Wed, 22-Nov-17 01:01

It is always great to follow experienced Java developers to keep track of news and updates. However, today, there are lots of voices trying to earn your attention, and they are not always right. We have searched high and low and created a list of the most resourceful and insightful Java experts for you to follow on social media.

Nicolas Fränkel

Categories: Java

Java: What to Know About Passing by Value

Javalobby Syndicated Feed - Tue, 21-Nov-17 22:01

Before describing how arguments are passed in Java, it is worth defining how Java variables are allocated in memory. Basically, we're talking about two types of variables: primitives and objects.

Primitive variables are always stored inside the stack memory (the memory space that holds method-specific variables that are short-lived in addition to references to other objects in the heap).

Categories: Java

Karaf Configuration as a Groovy File

Javalobby Syndicated Feed - Tue, 21-Nov-17 14:01

By default, Apache Karaf keeps configuration for bundles in the etc directory as flat properties files. We can override the configuration for the storing mechanism by providing our own implementation of the org.apache.felix.cm.PersistenceManager interface and use a much more readable format for bundle properties, e.g. Groovy config.

Turning Off Built-In Karaf Persistence

As we can read in the Karaf documentation:

Categories: Java

String Representation of Java Decimals Without Scientific Notation

Javalobby Syndicated Feed - Tue, 21-Nov-17 10:01

The primary types/objects used for decimal numbers in Java are float/Float, double/Double, and BigDecimal. Each of these has cases in which its "default" string representation is "computerized scientific notation." This post demonstrates some simple approaches to provide a string representation of the decimal number in these cases without scientific notation.

Examples in this post will demonstrate the "default" exponential String representations of these Java numeric types using a range of numbers for each type that demonstrates approximately where the "default" representation for each type becomes scientific notation. The next three code listings show the code for constructing general ranges for floats, doubles, and BigDecimals.

Categories: Java

Deploying Spring Apps to Tomcat (Without web.xml)

Javalobby Syndicated Feed - Tue, 21-Nov-17 04:01

Since the Servlet 3 specification, web.xml is no longer needed for configuring your web application and has been replaced by annotations. In this article, we will look at how to deploy a simple Spring-based application without web.xml to Tomcat 8.5.x.

Creating an Empty Application

Use the following command to create an empty web application using the Maven webapp archetype:

Categories: Java

Using JDK 10’s Local Variable Type Inference With jOOQ

Javalobby Syndicated Feed - Tue, 21-Nov-17 01:01

After the successful release of JDK 9, we can already look forward and play around with early access releases of JDK 10. The list of JEPs currently targeted for JDK 10 is quite manageable so far. JEP 286 is probably the most exciting one for most Java developers: Local variable type inference (which we’ve blogged about before). You can read the JEP yourself, or just go get the early access release and play around with it.

One of the nice things about this new feature is the fact that we now get access to non-denotable types that were previously rather clumsy to work with. For example, this is now possible:

Categories: Java

AJAX With CKEditor in Spring Boot

Javalobby Syndicated Feed - Mon, 20-Nov-17 22:01

In this article, we will cover how to use CKEditor with Spring Boot. In this tutorial, we will be importing an XML document with plenty of data, program the ability to load a set of data to the CKEditor instance with a GET request, and do a POST request to save the CKEditor's data.

Technologies we will be using include MongoDB, Thymeleaf, and Spring Batch.

Categories: Java

Scala Generics (Part 1): Scala Type Bounds

Javalobby Syndicated Feed - Mon, 20-Nov-17 14:01

Generic types, abstract types, scala type bounds: All these concepts are unusual for software developers who are coming from languages in which generics are not (or are barely) used. So, in this first article, we will discuss the basics and try to dig down only in type bounds.

Let's work with this little set of types and we will continuously modify the Parking type.

Categories: Java

YaaS.clj: A Clojure Client Library for Hybris-as-a-Service

Javalobby Syndicated Feed - Mon, 20-Nov-17 10:01

Recently, I decided to start a Clojure client library project for SAP Hybris as a Service (YaaS). But before the client library, let's see what YaaS is according to yaas.io and hybris.com

What Is SAP Hybris-as-a-Service (YaaS)?

YaaS is a microservices ecosystem helping businesses to rapidly augment and build new, highly flexible solutions.

Categories: Java

Which IDEs and Servers Support Java EE 8 and Java 9?

Javalobby Syndicated Feed - Mon, 20-Nov-17 04:01

I've been wanting to experiment with Java EE 8 and Java 9 as a continuation of my posts on Java 9. Seems simple enough, but it's actually quite hard to get a combination of IDEs and servers to work together.

The easy part of this problem is finding IDEs that support Java 9. All the major IDEs offer JDK support:

Categories: Java

Lombok's Extension Methods

Javalobby Syndicated Feed - Mon, 20-Nov-17 01:01

Spicing Java with Lombok!Let's talk about another excellent Lombok feature — @ExtensionMethod. An extension method is a feature of object-oriented-programming languages that allows methods defined outside of a class to be used with objects of that class (using the '.' operator) as if they are part of the class. Many programming languages such as C#, Scala, Kotlin, and TypeScript have this feature.

Java does not.

Categories: Java

Spring Batch CSV Processing

Javalobby Syndicated Feed - Sun, 19-Nov-17 22:01

Welcome! Topics we will be discussing today include the essential concepts of batch processing with Spring Batch and how to import the data from a CSV into a database.

Spring Batch CSV Processing Example Application

We are building an application that demonstrates the basics of Spring Batch for processing CSV files. Our demo application will allow us to process a CSV file that contains hundreds of records of Japanese anime titles.

Categories: Java

Handling RxJava Observables in a Web UI

Javalobby Syndicated Feed - Sat, 18-Nov-17 22:01

Before we dive into the meat of this article, let's start with some definitions.

RxJava: A Java VM implementation of Reactive Extensions: a library for composing asynchronous and event-based programs by using observable sequences. It is popular, as it addresses the concerns about low-level threading, synchronization, thread-safety and concurrent data structures.

Categories: Java

How Do Generic Subtypes Work?

Javalobby Syndicated Feed - Fri, 17-Nov-17 23:02

Generic classes are a powerful tool in any programming language, but they can also bring a great deal of confusion. For example, how come List<Double> is not a subclass of List<Number> even though Double is a subtype of Number? In this article, we will explore the various rules that surround subclassing generic types and build a cohesive view of the generic inheritance mechanism provided by Java. Before delving into this important topic, though, we will define the various different techniques for defining generic types and generic class arguments.

Understanding Generics

The purpose of generics in an object-oriented language is to allow for arbitrary aggregate types to be supplied to a class without having to write a new class for each of the supplied types. For example, if we wanted to write a list class to store objects, without generics we would be forced to either create a new class for each type passed (e.g. IntegerList, DoubleList, etc.) or have the internal structure of the list class store Objects as depicted in the listing below:

Categories: Java

Failing Fast With Java 8

Javalobby Syndicated Feed - Fri, 17-Nov-17 14:01

Fail fast or fail early is a software engineering concept that tries to prevent complex problems from happening by stopping execution as soon as something that shouldn't happen, well, happens.

In a previous blog post and presentation, I go more into detail about the merits of this approach, but in this blog post, I will just detail another use of this idea in Java 8.

Categories: Java

Thread Slivers eBook at Amazon

Syndicate content