Feed aggregator

Concourse Caching for Java Maven and Gradle Builds

Javalobby Syndicated Feed - 3 hours 14 min ago

Concourse CI 3.3.x has introduced the ability to cache paths between task runs. This feature helps speed up tasks which cache content in specific folders — here I will demonstrate how this feature can be used for speeding up Maven- and Gradle-based Java builds.

The code and the pipeline that I am using for this post is available at my GitHub repo here.

Categories: Java

New RegEx Features in Java 9

Javalobby Syndicated Feed - 7 hours 14 min ago

I recently received my complimentary copy of the book “Java 9 Regular Expressions” from Anubhava Srivastava published by Packt. The book is a good tutorial and introduction to anyone who wants to learn what regular expressions are and start from scratch. For those who know how to use RegEx, the book may still be interesting to reiterate the knowledge and to deepen into more complex features like zero length assertions, back references, and the like.

In this article, I will focus on the few regular expression features that are specific to Java 9 and were not available in earlier version of the JDK.

Categories: Java

What Is javax.ws.rs.core.context? (Part 1)

Javalobby Syndicated Feed - 13 hours 14 min ago

The JAX-RS API provides a very handy mechanism to inject a range of useful resources, such as HTTP Headers, into your endpoint. The @Context annotation is an all-purpose annotation that injects instances of the following objects:

  • HttpHeaders -> HTTP header parameters and values
  • UriInfo -> Captures path variables and query parameters
  • SecurityContext -> Provides access to security related information for a request
  • ResourceContext -> Provides access to instances of resource classes
  • Request -> Precondition request processing
  • Application, Configuration, and Providers -> Provide information about the JAX-RS application environment
  • HttpServletRequest -> Provides access to the HttpServletRequest instance
  • HttpServletResponse -> Provides access to the HttpServletResponse instance
  • ServletConfig -> Provides access to the ServletConfig
  • ServletContext -> Provides access to the ServletContext

Let’s examine each in turn with working code examples.

Categories: Java

Not everything that is vital is also your core business

codecentric Blog - 15 hours 39 min ago

Large software projects have many vital concerns, such as authentication and authorization. Despite the wealth of available libraries in the Java ecosystem we seem to be re-inventing the wheel far too often. Keep the focus on the core business of your application and don’t think you can code quicker and cheaper yourself than what you can buy off the shelf.

Some ten years ago the consultancy company in Rotterdam I was working for at the time was in the process of migrating their physical servers (JBoss/Oracle) to the cloud. Two modest server racks hogging an air-conditioned room didn’t make good business sense. I can remember a verbal scuffle between our then head of IT and a few more traditional forces in the development team who kept harping on that “these machines are our core business”. Of course they weren’t. In the end nothing much changed for the devs. The care for the now virtualized machines – that were indeed vital to the running of the company – was outsourced and no disasters ever happened.

Don’t grind your own flour

If you’re a travelling sales rep your car is vital, but talking to customers is your core business.
If you’re headmaster of a school you need heating and running water in the building, but your core business is with managing your teaching staff and talking to parents.
As to myself, I can’t do my job without my MacBook Pro, but… You get the point. Most of what is indispensable to completing a job or running a business can be bought, hired or downloaded. Adding value is what drives the economy. We even have a tax for it.

In the not-so good old days providing food and shelter to keep you and your family from starving and freezing to death was pretty much everybody’s core business. It is specialised job descriptions like feelgood manager that separate us from these ancestors. Just as the baker doesn’t grind his own flour to bake a cake, I don’t write my own device drivers or hashing algorithms (more on that later). Mind you, some do, just for the fun of it.


Re-inventing the wheel is a counter-intuitive practice, but we see it all the time. There’s the not-invented-here syndrome: unlikely to be included in the DSM manual of mental disorders but a disease nonetheless. Let’s be fair: to do an incomplete buggy rewrite under the mistaken idea that you can do it better or quicker is wilfully squandering your employer’s money. These people shouldn’t be allowed to make strategic decisions without adult supervision.

Do you sometimes find yourself coding a specific problem, feeling certain that you’re not the first one grappling with this particular problem and wonder if there might not be something you could pull off the shelf? You are probably right and there very likely is something on the shelf.

DDIY: Don’t do it yourself

Every networked multi-user application needs some form of authentication (who are you?) and authorisation (what are you allowed to do). Let me coin the phrase commodity concern here. Secure authentication is non-trivial to implement from scratch and it has dire consequences if you get it wrong. It’s also a necessary evil keeping you from coding the added value of your product that (hopefully) nobody else is writing at the same time. Now of course you don’t write all this from scratch. Spring security has libraries for all your authentication needs. Which is exactly the problem: it’s a DIY kit. There are live wires sticking out for you to connect. While creating and storing  password hashes I was prompted to “choose a sufficiently large number of log rounds” for the BCrypt library (apparently too much can fry your CPU). How am I expected to know? Does the anaesthesiologist ask the patient how many milligrams of propofol they would like?

If only I had known keycloak, an open source identity and access management server. Our colleague Jannik Hüls gave a fascinating talk recently at our Breda office.
Instead of cobbling together your authentication solution out of library components and layers of configuration glue, you delegate everything to keycloak and configure multiple realms for multiple apps for any number of protocols through its admin portal. Yes, there’s some unavoidable glue code required to hook it up to your app, but considering the wealth of features it offers out of the box (user registration and admin, email validation), this is minimal.

Cheer up: the hard stuff is already done

In a language like Java most of the hard and challenging commodity stuff has already been done by people smarter than yourself. If you like implementing sort algorithms you can always choose a hip new language with a still embryonic ecosystem. A savvy Java developer should know when not to code. Some might bemoan that this degrades the art of building software to glueing together components, but I disagree. The necessary ‘forgot your password?’ page may be a valid use case, but it’s a commodity concern. It’s vital but repetitious and hence dull.

In one of my previous posts I stressed that you cannot explore enough. There is so much great stuff out there that can save you time if only you took the time to find it. It won’t always be love at first sight. Sometimes you absorb it just enough to realise it’s not your cup of tea. Other times you recognise the value, but don’t have a use for it in a present project. Maybe later, that’s fine. But you have to know it exists in the first place.


The post Not everything that is vital is also your core business appeared first on codecentric AG Blog.

Categories: Agile, Java, TDD & BDD

jOOQ Tuesdays: Let's Talk About Spring Data

Javalobby Syndicated Feed - 16 hours 14 min ago

Welcome to the jOOQ Tuesdays series. In this series, we’ll publish an article on the third Tuesday every other month where we interview someone we find exciting in our industry from a jOOQ perspective. This includes people who work with SQL, Java, open source, and a variety of other related topics.

I’m very excited to feature today Oliver Gierke, the Spring Data Project Lead at Pivotal with strong opinions on DDD and REST.

Categories: Java

9 Best Practices to Handle Exceptions in Java

Javalobby Syndicated Feed - 19 hours 14 min ago

Exception handling in Java isn’t an easy topic. Beginners find it hard to understand and even experienced developers can spend hours discussing how and which exceptions should be thrown or handled.

That’s why most development teams have their own set of rules on how to use them. And if you’re new to a team, you might be surprised how different these rules can be to the ones you’ve used before.

Categories: Java

The Best Java IDEs and What to Expect From Them [Infographic]

Javalobby Syndicated Feed - Wed, 16-Aug-17 10:01

As you know, Java IDEs allow developers to write and debug Java programs with ease. A good IDE will have a number of features that help developers to write code easily. The features include debugging, easy editing, toggling of views, and so on.

Your choice of an IDE will depend on a number of factors — nature of the project, your team/organization’s preference, and so on. But there are some basic, non-negotiable requirements that every good IDE has to meet.

Categories: Java

Handling Custom Objects With JAX-RS SSE API

Javalobby Syndicated Feed - Wed, 16-Aug-17 06:01

Information sent using JAX-RS 2.1 SSE support (in Java EE 8) does not only have to be of String type – it supports Java primitives (Integer , Long etc.), JSON-B and JAX-B annotated types as well as custom objects whose encoding process (Java object to on-wire format) is defined using a MessageBodyWriter implementation

Here is a simple example you can try out – no need to setup anything except Docker !

Categories: Java

Testing with GoMock: A Tutorial

codecentric Blog - Wed, 16-Aug-17 01:00

This is a quick tutorial on how to test code using the GoMock mocking library and the standard library testing package testing.

GoMock is a mock framework for Go. It enjoys a somewhat official status as part of the github.com/golang organization, integrates well with the built-in testing package, and provides a flexible expectation API.

The code snippets referenced in this post are available on GitHub: github.com/sgreben/testing-with-gomock.



First, we need to install the gomock package github.com/golang/mock/gomock as well as the mockgen code generation tool github.com/golang/mock/mockgen. Technically, we could do without the code generation tool, but then we’d have to write our mocks by hand, which is tedious and error-prone.

Both packages can be installed using go get:

go get github.com/golang/mock/gomock
go get github.com/golang/mock/mockgen

We can verify that the mockgen binary was installed successfully by running


This should output usage information and a flag list. Now that we’re all set up, we’re ready to test some code!

Basic Usage

Usage of GoMock follows four basic steps:

  1. Use mockgen to generate a mock for the interface you wish to mock.
  2. In your test, create an instance of gomock.Controller and pass it to your mock object’s constructor to obtain a mock object.
  3. Call EXPECT() on your mocks to set up their expectations and return values
  4. Call Finish() on the mock controller to assert the mock’s expectations

Let’s look at a small example to demonstrate the above workflow. To keep things simple, we’ll be looking at just two files — an interface Doer in the file doer/doer.go that we wish to mock and a struct User in user/user.go that uses the Doer interface.

The interface that we wish to mock is just a couple of lines — it has a single method DoSomething that does something with an int and a string and returns an error:


package doer

type Doer interface {
    DoSomething(int, string) error

Here’s the code that we want to test while mocking out the Doer interface:


package user

import "github.com/sgreben/testing-with-gomock/doer"

type User struct {
    Doer doer.Doer

func (u *User) Use() error {
    return u.Doer.DoSomething(123, "Hello GoMock")

Our current project layout looks as follows:

'-- doer
    '-- doer.go
'-- user
    '-- user.go

We’ll put the mock for Doer in a package mocks in the root directory and the test for User in the file user/user_test.go:

'-- doer
    '-- doer.go
'-- mocks
    '-- mock_doer.go
'-- user
    '-- user.go
    '-- user_test.go

We start by creating a directory mocks that will contain our mock implementations and then running mockgen on the doer package:

mkdir -p mocks
mockgen -destination=mocks/mock_doer.go -package=mocks github.com/sgreben/testing-with-gomock/doer Doer

Here, we have to create the directory mocks ourselves because GoMock won’t do it for us and will quit with an error instead. Here’s what the arguments given to mockgen mean:

  • -destination=mocks/mock_doer.go: put the generated mocks in the file mocks/mock_doer.go.
  • -package=mocks: put the generated mocks in the package mocks
  • github.com/sgreben/testing-with-gomock/doer: generate mocks for this package
  • Doer: generate mocks for this interface. This argument is required — we need to specify the interfaces to generate mocks for explicitly. We can, however specify multiple interfaces here as a comma-separated list (e.g. Doer1,Doer2).

If $GOPATH/bin was not in our $PATH, we’d have to call mockgen via $GOPATH/bin/mockgen. In the following we’ll assume that we have $GOPATH/bin in our $PATH.

As a result, our invocation of mockgen places a file mocks/mock_doer.go in our project. This is how such a generated mock implementation looks:


// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/sgreben/testing-with-gomock/doer (interfaces: Doer)

package mocks

import (
	gomock "github.com/golang/mock/gomock"

// MockDoer is a mock of Doer interface
type MockDoer struct {
	ctrl     *gomock.Controller
	recorder *MockDoerMockRecorder

// MockDoerMockRecorder is the mock recorder for MockDoer
type MockDoerMockRecorder struct {
	mock *MockDoer

// NewMockDoer creates a new mock instance
func NewMockDoer(ctrl *gomock.Controller) *MockDoer {
	mock := &MockDoer{ctrl: ctrl}
	mock.recorder = &MockDoerMockRecorder{mock}
	return mock

// EXPECT returns an object that allows the caller to indicate expected use
func (_m *MockDoer) EXPECT() *MockDoerMockRecorder {
	return _m.recorder

// DoSomething mocks base method
func (_m *MockDoer) DoSomething(_param0 int, _param1 string) error {
	ret := _m.ctrl.Call(_m, "DoSomething", _param0, _param1)
	ret0, _ := ret[0].(error)
	return ret0

// DoSomething indicates an expected call of DoSomething
func (_mr *MockDoerMockRecorder) DoSomething(arg0, arg1 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "DoSomething", arg0, arg1)

Note that the generated EXPECT() method is defined on the same object as the mock methods (in this case, DoSomething) — avoiding name clashes here is likely a reason for the non-standard all-uppercase name.

Next, we define a mock controller inside our test. A mock controller is responsible for tracking and asserting the expectations of its associated mock objects.

We can obtain a mock controller by passing a value t of type *testing.T to its constructor, and then use it to construct a mock of the Doer interface. We also defer its Finish method — more on this later.

mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()

mockDoer := mocks.NewMockDoer(mockCtrl)

Suppose we want to assert that mockerDoer‘s Do method will be called once, with 123 and "Hello GoMock" as arguments, and will return nil.

To do this, we can now call EXPECT() on the mockDoer to set up its expectations in our test. The call to EXPECT()returns an object (called a mock recorder) providing methods of the same names as the real object.

Calling one of the methods on the mock recorder specifies an expected call with the given arguments. You can then chain other properties onto the call, such as:

  • the return value (via .Return(...))
  • the number of times this call is expected to occur (via .Times(number), or via .MaxTimes(number) and .MinTimes(number))

In our case, the call looks like this:

mockDoer.EXPECT().DoSomething(123, "Hello GoMock").Return(nil).Times(1)

That’s it – we’ve now specified our first mock call! Here’s the complete example:


package user_test

import (

func TestUse(t *testing.T) {
    mockCtrl := gomock.NewController(t)
    defer mockCtrl.Finish()

    mockDoer := mocks.NewMockDoer(mockCtrl)
    testUser := &user.User{Doer:mockDoer}

    // Expect Do to be called once with 123 and "Hello GoMock" as parameters, and return nil from the mocked call.
    mockDoer.EXPECT().DoSomething(123, "Hello GoMock").Return(nil).Times(1)


Probably, it’s not obvious where in the code the mock’s expectations are asserted. This happens in the deferred Finish(). It’s idiomatic to defer this call to Finish at the point of declaration of the mock controller — this way we don’t forget to assert the mock expectations later.

Finally, we’re ready to run our tests:

$ go test -v github.com/sgreben/testing-with-gomock/user
=== RUN   TestUse
--- PASS: TestUse (0.00s)
ok      github.com/sgreben/testing-with-gomock/user     0.007s

If you need to construct more than one mock, you can reuse the mock controller — its Finish method will then assert the expectations of all mocks associated with the controller.

We might also want to assert that the value returned by the Use method is indeed the one returned to it by DoSomething. We can write another test, creating a dummy error and then specifying it as a return value for mockDoer.DoSomething:


func TestUseReturnsErrorFromDo(t *testing.T) {
    mockCtrl := gomock.NewController(t)
    defer mockCtrl.Finish()

    dummyError := errors.New("dummy error")
    mockDoer := mocks.NewMockDoer(mockCtrl)
    testUser := &user.User{Doer:mockDoer}

    // Expect Do to be called once with 123 and "Hello GoMock" as parameters, and return dummyError from the mocked call.
    mockDoer.EXPECT().DoSomething(123, "Hello GoMock").Return(dummyError).Times(1)

    err := testUser.Use()

    if err != dummyError {

Using GoMock with go:generate

Running mockgen for each package and interface individually is cumbersome when there is a large number of interfaces/packages to mock. To alleviate this problem, the mockgen command may be placed in a special go:generate comment.

In our example, we can add a go:generate comment just below the package statement of our doer.go:


package doer

//go:generate mockgen -destination=../mocks/mock_doer.go -package=mocks github.com/sgreben/testing-with-gomock/doer Doer

type Doer interface {
    DoSomething(int, string) error

Note that at the point where mockgen is called, the current working directory is doer — hence we need to specify ../mocks/ as the directory to write our mocks to, not just mocks/.

We can now comfortably generate all mocks specified by such a comment by running

go generate ./...

from the project’s root directory. Note that there is no space between // and go:generate in the comment. This is required for go generate to pick up the comment as an instruction to process.

A reasonable policy on where to put the go:generate comment and which interfaces to include is the following:

  • One go:generate comment per file containing interfaces to be mocked
  • Include all interfaces to generate mocks for in the call to mockgen
  • Put the mocks in a package mocks and write the mocks for a file X.go into mocks/mock_X.go.

This way, the mockgen call is close to the actual interfaces, while avoiding the overhead of separate calls and destination files for each interface.

Using argument matchers

Sometimes, you don’t care about the specific arguments a mock is called with. With GoMock, a parameter can be expected to have a fixed value (by specifying the value in the expected call) or it can be expected to match a predicate, called a Matcher. Matchers are used to represent ranges of expected arguments to a mocked method. The following matchers are pre-defined in GoMock:

  • gomock.Any(): matches any value (of any type)
  • gomock.Eq(x): uses reflection to match values that are DeepEqual to x
  • gomock.Nil(): matches nil
  • gomock.Not(m): (where m is a Matcher) matches values not matched by the matcher m
  • gomock.Not(x): (where x is not a Matcher) matches values not DeepEqual to x

For example, if we don’t care about the value of the first argument to Do, we could write:

mockDoer.EXPECT().DoSomething(gomock.Any(), "Hello GoMock")

GoMock automatically converts arguments that are not of type Matcher to Eq matchers, so the above call is equivalent to:

mockDoer.EXPECT().DoSomething(gomock.Any(), gomock.Eq("Hello GoMock"))

You can define your own matchers by implementing the gomock.Matcher interface:

gomock/matchers.go (excerpt)

type Matcher interface {
    Matches(x interface{}) bool
    String() string

The Matches method is where the actual matching happens, while String is used to generate human-readable output for failing tests. For example, a matcher checking an argument’s type could be implemented as follows:


package match

import (

type ofType struct{ t string }

func OfType(t string) gomock.Matcher {
    return &ofType{t}

func (o *ofType) Matches(x interface{}) bool {
    return reflect.TypeOf(x).String() == o.t

func (o *ofType) String() string {
    return "is of type " + o.t

We can then use our custom matcher like this:

// Expect Do to be called once with 123 and any string as parameters, and return nil from the mocked call.
    DoSomething(123, match.OfType("string")).

We’ve split the above call across multiple lines for readability. For more complex mock calls this is a handy way of making the mock specification more readable. Note that in Go we have to put the dot at the end of each line in a sequence of chained calls. Otherwise, the parser will consider the line ended and we’ll get a syntax error.

Asserting call order

The order of calls to an object is often important. GoMock provides a way to assert that one call must happen after another call, the .After method. For example,

callFirst := mockDoer.EXPECT().DoSomething(1, "first this")
callA := mockDoer.EXPECT().DoSomething(2, "then this").After(callFirst)
callB := mockDoer.EXPECT().DoSomething(2, "or this").After(callFirst)

specifies that callFirst must occur before either callA or callB.

GoMock also provides a convenience function gomock.InOrder to specify that the calls must be performed in the exact order given. This is less flexible than using .After directly, but can make your tests more readable for longer sequences of calls:

    mockDoer.EXPECT().DoSomething(1, "first this"),
    mockDoer.EXPECT().DoSomething(2, "then this"),
    mockDoer.EXPECT().DoSomething(3, "then this"),
    mockDoer.EXPECT().DoSomething(4, "finally this"),

Under the hood, InOrder uses .After to chain the calls in sequence.

Specifying mock actions

Mock objects differ from real implementations in that they don’t implement any of their behavior — all they do is provide canned responses at the appropriate moment and record their calls. However, sometimes you need your mocks to do more than that. Here, GoMock‘s Do actions come in handy. Any call may be decorated with an action by calling .Do on the call with a function to be executed whenever the call is matched:

    DoSomething(gomock.Any(), gomock.Any()).
    Do(func(x int, y string) {
        fmt.Println("Called with x =",x,"and y =", y)

Complex assertions about the call arguments can be written inside Do actions. For example, if the first (int) argument of DoSomething should be less than or equal to the length of the second (string) argument, we can write:

    DoSomething(gomock.Any(), gomock.Any()).
    Do(func(x int, y string) {
        if x > len(y) {

The same functionality could not be implemented using custom matchers, since we are relating the concrete values, whereas matchers only have access to one argument at a time.


In this post, we’ve seen how to generate mocks using mockgen and how to batch mock generation using go:generate comments and the go generate tool. We’ve covered the expectation API, including argument matchers, call frequency, call order and Do-actions.

If you have any questions or if you feel that there’s something missing or unclear, please don’t hesitate to let me know in the comments!

The post Testing with GoMock: A Tutorial appeared first on codecentric AG Blog.

Categories: Agile, Java, TDD & BDD

This Week in Spring - August 15th, 2017

Javalobby Syndicated Feed - Tue, 15-Aug-17 22:02

Hi Spring fans and welcome to another installment of This Week in Spring! It’s been a busy week! I started last week talking to a group of developers in North Carolina, then gave a VJUG presentation with Matt Raible in San Francisco, then spoke to developers in Saint Louis, then flew to New York City to shoot a video on continuous delivery for three days in a hot studio (over the weekend no less!) and now as I wing back to San Francisco I look forward to spending a blissful 14 hours on the ground before I’m off to Asia (Hangzhou, Shanghai, Beijing, Shenzhen, Hong Kong, and Singapore) for about four weeks! I’m not the only one who’s been busy, though! As usual, we’ve got a lot to cover this week so let’s get to it!

  • My friend and Spring Framework lead Juergen Hoeller gave a talk introducing reactive programming with Spring at Devoxx PL 2017. I hope you’ll watch this one if you watch anything.
  • My buddy Matt Raible and I did a presentation last week that looked at building progressive web applications and robust backend services with Angular and Spring Boot. Matt and I have given this talk a few times and it’s always fun. We do the talk live. I write the backend services and he writes the front-end client. I write the backend service using Apache Groovy, Kotlin, and Java. He uses TypeScript in the front-end. I think Matt’s the real hero here, of course, because even though I wrote 3 services, Matt ended up writing reams more TypeScript to get a client working! This video was crazy fun. I hope you’ll check it out.
  • Cloud Native Java is finally done and shipping! My friend Kenny Bastani and I wrote a little book for O’Reilly - Cloud Native Java - on how to build cloud native Java applications in terms of Spring Boot, Spring Cloud, and Cloud Foundry. The book took us two years, has been reviewed a zillion different ways by folks on the Spring team, has forwards by Spring creator Rod Johnson and Cloud Foundry legend James Watters. It’s not the worst book that you could buy, and I hope you’ll consider it. Thanks so much for your patience, Spring fans!
  • SpringOne Platform 2017, held in the Moscone center in beautiful San Francisco, CA, is in four short months! I’m going and I hope you will too. If you need more convincing, read this. If you’re already convinced then click that link for the ridiculous animated .gif that the marketing team put together!
  • I am absolutely loving the Spring Framework 5 reference documentation
  • I liked this pull-request. It’s by no means a definitive look at what will be supported or not supported, but the comments are interesting. It looks at what Spring Boot 2 might support HTTP 2 by default. Perhaps it’s a Java 9-only feature? Maybe there’s an appetite to explore some of the truly wretched options required to make it work on Java 8? If you have ideas or want to learn more, check out this issue!
  • Have you seen the new Spring Getting Started guide on messaging with Google Cloud Pub/Sub?
  • This Codecentric post looks at how to parse Java 8 LocalDate query parameters with a given date format.
  • Matthew Casperson looks at adding Spring Security to a Spring Boot-based project. Short and sweet - just the way it should be! Nice job Matthew!
  • This DZone RefCard is a pretty good introduction to using Google Cloud. I have really grown to like Google Cloud - it provides a lot of business-differentiating functionality all while being an amazing place to run Cloud Foundry.
  • My friend John Willis looks at different models - PDCA and OODA - for organizational orientation; how to figure out what to do next based on what’s happened. This has nothing to do with Spring, per se, and everything with building the right thing (with Spring).
  • This week I spent a few days in studio shooting more content - this time looking at continuous delivery in terms of the Spring and Pivotal ecosystems - with my friend (and Pivotal’s resident continuous delivery mad-scientist) Marcin Grzejszczak. All this to say we spend a non-negative number of minutes dissecting JSON Path in the video and it seemed a propos to remind folks of the JSON Path project itself and this post introducing JSON Path from the Baeldung blog.
  • The Okta blog is on fire since the Stormpath team-meld! So much great content, seemingly every day! Here’s a nice post on securing Spring Boot applications with Apache Shiro, for those that do that sort of thing.
  • Also from the Okta blog this last week, Matt Raible’s epic post that looks at how to secure Spring Boot and Spring Cloud microservices using JWTs, Juiser, and Okta. Nice job Matt!
  • Congratulations to the Reactive Streams teams who just last week announced that Reactive Streams 1.0.1 is here!
  • Auth0’s security with Spring Boot game is pretty on point, too! This week they released a useful look at securing Spring Boot applications with JSON Web Tokens (JWTs). Nice job!
  • Atomist co-founder Russ Miles looks at their collaboration tool’s ability to smoothly support a pull-request workflow. They do so in the context of an application (which happens to be written in Spring Boot) and while referencing Spring Boot in a post isn’t in of itself normally enough to be worthy of inclusion in these humble paragraphs, Atomist is generally so cool I’ll make an exception!
  • Congratulations to the Kotlin team at JetBrains on the new Kotlin 1.2.M2 release, looks terrific. It includes new APIs supporting mathematics that work in a uniform way across the JVM and JavaScript runtimes for Kotlin. Now’s a good time to kick the tires and try the new features, perhaps using the Spring Boot Initializr?
  • Redmonk has a great post on Spring Boot users New Relic and the Tesla - in the field who’ve recently published their use.
  • The YouTube playlist for the Seoul, Korea-based Spring Camp event and all of its wonderful Pivotal and Spring-centric content (in Korean!) is now available. This is a wonderful resource for Korean speakers!
  • This Portuguese-language book on Spring Boot - Spring Boot: Acelere o desenvolvimento de microsserviços looks like it could be a good read.
  • Bernd Rücker from the Camunda BPM team has put out a very cool example of integrating Camunda BPM with Spring Boot in a distributed application. The README is almost as interesting as the code itself, too. I love the discussion of testing which is something that’s typically missing from higher-level tools like workflow engines.

Categories: Java

Default and Private Methods in Interfaces

Javalobby Syndicated Feed - Tue, 15-Aug-17 09:01

In this tutorial, we will look at default and private methods within interfaces. Default methods were added in Java 8, allowing methods to be added to an interface that comes with a default implementation that could be used, overridden, or ignored without causing issues to existing classes that have implemented an interface.

Private methods were missing when default methods were added, preventing code from being split out into smaller methods within an interface. This is something that was a bit off-putting to me, as if you had a default method that became a bit long, there was no way to tidy it up. So now that both default and private methods can exist within an interface, we can write methods like we are used to, although if you haven’t used default methods yet, then you will first need to get past the fact that there is now actual code living in an interface.

Categories: Java

How and when to use JSON Web Tokens for your services

codecentric Blog - Tue, 15-Aug-17 08:02

There are multiple ways to allow a service to be used securely. JSON web tokens is one of them, although there are limitations to the security that JSON web tokens provide. JSON Web tokens(JWT) is a standard for representing claims securely between two parties. It is quite secure because the JWT can be signed using a secret or public/private key.

What is a JSON web token?

The JWT has three parts separated with dots. These parts are the header, payload and signature. So it will look like this ‘xxxxx.yyyyy.zzzzz’. The header could look like this:

"alg": "HS256",
"typ": "JWT"

With ‘alg’ meaning the algorithm for hashing or encryption. The header will be encoded separately.
The payload contains the claims which are statements about an entity. There are reserved claims that are predefined and can be used by anyone, like exp (expiration date) and sub (subject)

"sub": "Login",
"exp": "1408621000",
"admin": true

In this case ‘exp’ is a NumericDate value. This is a numeric value in seconds since 1970-01-01. You can generate an ‘exp’ value using this javascript:

let exp = Math.floor(Date.now() / 1000) + secondsBeforeExpiration

The signature is the last part of JWT and takes the encoded header and payload, and signs these using the algorithm and secret. This is shown in pseudo code below:

let signature = RS256Algorithm(encode64(header) + "." + encode64(payload) , secret);

To create the full JWT:

let jwt = encode64(header) + "." + encode64(payload) + "." + signature;

The JWT will look like this:


To use the JWT you get from a server the client should add the JWT in the header of a request like this:

Authorization: Bearer :token:

So to conclude this very brief introduction of JWTs we have an encoded message with an encrypted signature which can not be changed, otherwise the payload and header will lead to another signature.
This built-in security makes it very hard for others to generate a valid token, which can only be done by somehow guessing the secret correctly.

A possible weak spot in JWT is that you can change the algorithm from RS256 to HS256. In this case the public key will be used for verification because the signature is compared to a HMAC of the token where the public key is used as the secret. So you should verify the ‘alg’ value in the token with the algorithm on the server. In the following links you can find more information.


How to use JSON web tokens?

So what could an architecture using stateless JWT’s look like? A very simple example is given below.

You have three services (S1, S2, Auth) with one service (S1) that wants to consume the output of the other service (S2). There is also an authentication service (Auth) that manages tokens and allows requests for a token. A token will be requested at the authentication service by S1, which allows an update of data in S2. S1 will identify itself, and the authentication service knows it can provide the token to S1 for updates and create calls on S2.

But what do we win with tokens in this architecture? Firstly, we now know that the server gained a token with a claim that is valid and not tampered with. In this case a claim that gives access to perform an action on another service. The token does not contain a reference to any data on the server but contains the data itself. A problem is that the data in the token can go stale due to changes in the web application, for example when the access rights for the token owner are revoked on the authentication server, but the token will still be accepted by the services.

The tokens have a short time till they expire, so in this short time the server S1 is able to do certain requests to S2. Expiration is needed so S1 needs to acquire a new token at certain moments, preventing said problems of stale data. S1 is free to do as many requests as possible till the token expires. In this case the token itself cannot be revoked before expiration because the server does not keep track of it.

This example of the so called stateless JSON web tokens shows it can play a specific role, but the fact that they are out there and untracked is often a problem. It useful to serve in a short time span and with predefined actions that are accessible the whole time span.
Something like a short online auction where each user gets a token to be allowed to do a bid call on the server for, let’s say, 20 minutes. Making sure the token does not fall in the wrong hands would still be a problem to solve, but JWT makes sure the client bid data is not meddled with.

A nice thing about stateless JWTs is that you can do local authentication which prevents an extra call. You just provide the secret to your load balancers, for example. They all can validate the token and the client can easily switch.

So JWTs that are tracked by a server behave actually much like sessions and you should ask yourself if you want to use them. Something to take into account is that JWTs will be quite big compared to a session id, so this means bigger calls. JWTs were brought as a stateless authentication solution and here it gets really interesting that this is possible, yet often this is not what you want.
There are some excellent blog posts about the problems with stateless JWTs.


To conclude, there are good frameworks for authentication which will use JWTs themselves, and you probably don’t need to implement your own authentication service. For example, the open source Keycloak solution or LoginRadius solution both support JWTs and also other identity functionality. But when you want to implement some solution yourself, take into account that JWTs can be a stateless solution, but often you don’t need stateless authentication token or it’s safer not to have such a solution.

The post How and when to use JSON Web Tokens for your services appeared first on codecentric AG Blog.

Categories: Agile, Java, TDD & BDD

How Memory Leaks Happen in Java Apps

Javalobby Syndicated Feed - Tue, 15-Aug-17 03:01

One of the core benefits of Java is the JVM, which is an out-of-the-box memory management. Essentially, we can create objects and the Java Garbage Collector will take care of allocating and freeing up memory for us.

Nevertheless, memory leaks can still occur in Java applications.

Categories: Java

7 Reasons Converting COBOL to Java to Save Cash Is a Red Herring

Javalobby Syndicated Feed - Tue, 15-Aug-17 00:01

Companies are having discussions about reducing CPU costs through the wholesale conversion of COBOL applications to Java. Inviting as it seems at first glance, this option of reducing costs may be short-lived and is a red herring because of unrealized issues and problems that occur when converting entire applications to Java.

This first of a series of blogs starts with an overview of what’s involved in converting COBOL to Java, with emphasis on pitfalls that may not be obvious. Some information about major conversion issues is presented and discussed at a high level with references to pertinent literature.

Categories: Java

An Intro to Spring Boot With Spring Data Mongo

Javalobby Syndicated Feed - Mon, 14-Aug-17 21:01

Dark times are ahead for the Justice League with the formidable Darkseid coming over to conquer human kind. Batman, with the help of Wonder Woman, is on a quest to get the league together with one critical aspect missing — a proper Justice League member management system.

As time is not on their side, they do not want to go through the cumbersome process of setting up a project from scratch with all the things they need. Batman hands over this daunting task of building a rapid system to his beloved trusted Alfred (as Robin is so unpredictable), who tells Batman that he recalls coming across something called Spring Boot, which helps set up everything you need so you can get to writing code for your application rather than being bogged down with the minor nuances of setting up the configuration for your project.

Categories: Java

Understanding the Use Cases of Java Generics

Javalobby Syndicated Feed - Mon, 14-Aug-17 13:01

Understanding general use cases of generics solves half of the problem. First things first, we should know what they are, why to consider them, and where they apply.

What Is It?

Consider a simple add method, seen below. You cannot pass long, float, or double types as inputs to this method, right?

Categories: Java

Spring Cloud Config (Part 3): ZooKeeper Backend

Javalobby Syndicated Feed - Mon, 14-Aug-17 09:01

In this part of the series, we take a look at how we can use Spring Cloud Config with ZooKeeper to manage our configuration.


I’ve always found it hard to define what ZooKeeper is. This is the definition given on its website:

Categories: Java

Java Command-Line Interfaces (Part 11): CmdLn

Javalobby Syndicated Feed - Mon, 14-Aug-17 03:01

This post describes using Ostermiller Java Utilities 1.08.02's CmdLn (Java Command Line Parser) to process command-line arguments from Java-based applications. The Ostermiller Java Utilities include several different types of utilities, but the focus of this post is on the "Command Line Parser" that is described on the components page, "Handle options and arguments to Java command line programs."

The Ostermiller Utilities command line parser does not use annotations, but instead employs the programmatic builder with fluent API concepts that some of the other Java-based command-line parsing libraries have also used instead of annotations. The classes com.Ostermiller.util.CmdLn and com.Ostermiller.util.CmdLnOption are used together in the "definition" stage of command-line processing with CmdLn. This is demonstrated in the next code listing.

Categories: Java

5 Things You May Not Have Known About jOOQ

Javalobby Syndicated Feed - Mon, 14-Aug-17 00:01

jOOQ has been around for a while now (since 2009!) and by now we can say we’ve seen quite a bit about the SQL and Java languages. Some of our design decisions are particular in the way jOOQ thinks about programming with SQL. These include:

  • Nullability (let’s stop fighting it)
  • Value types (let’s stop pretending SQL has identities)
  • Everything is a table (this really helps get the most out of SQL)
  • Queries are side-effect free functions

jOOQ incorporates all of these ideas. With that in mind, here are five things you might not have known about jOOQ.

Categories: Java

Thread Slivers eBook at Amazon

Syndicate content