Feed aggregator

Java Memory Management

Javalobby Syndicated Feed - Sat, 06-Jan-18 23:01

You might think that if you are programming in Java, what do you need to know about how memory works? Java has automatic memory management, a nice and quiet garbage collector that quietly works in the background to clean up the unused objects and free up some memory.

Therefore, you as a Java programmer do not need to bother yourself with problems like destroying objects, as they are not used anymore. However, even if this process is automatic in Java, it does not guarantee anything. By not knowing how the garbage collector and Java memory is designed, you could have objects that are not eligible for garbage collecting, even if you are no longer using them.

Categories: Java

7 Things to Know Getting Started With Spring Boot

Javalobby Syndicated Feed - Fri, 05-Jan-18 23:01

Spring Boot is a tricky framework to understand. In this tutorial for beginnners with Spring Boot, we will look at the basics of Spring Boot and help you understand the important concepts — Starter Projects, Auto Configuration, and Starter Parents.

Understanding Spring Boot's Architecture

The building blocks of Spring Boot are:

Categories: Java

Kotlin: The Tuple Type

Javalobby Syndicated Feed - Fri, 05-Jan-18 14:01

It is very easy to write a Tuple type with the expressiveness of Kotlin. My objective, expressed in tests, is the following:

  1. Be able to define a Tuple of up to 5 elements and be able to retrieve the elements using an index like a placeholder in a test expressed with 2 elements, like this:
  2. val tup = Tuple("elem1", "elem2")
    assertThat(tup._1).isEqualTo("elem1")
    assertThat(tup._2).isEqualTo("elem2")


Categories: Java

Binding Properties From External Sources in Spring Boot Apps

Javalobby Syndicated Feed - Fri, 05-Jan-18 04:01

As per Spring's documentation, Spring Boot allows us to externalize configurations, so you can work with the same application code in different environments. You can use property files, YAML files, environment variables, and command-line arguments to externalize configurations. But in this article we will mostly check how to read configurations from property or yml files. True externalization requires reading property or YAML files from external cloud sources like Consul, where Consul properties like consul host, port, and keys are provided to the application via environment variables. Then our same application code can run in different environments. We will cover that in some other article.

Here, we will discuss how configuration keys are bound to actual objects in Spring Boot applications. The most basic way to bind your configurations is from property or YAML files to POJO classes, which we can use later in the lifecycle of our application.

Categories: Java

Run Code on Startup With Play and Scala

Javalobby Syndicated Feed - Fri, 05-Jan-18 01:01

Depending on various projects, sometimes there is a need to execute some actions on initialization, just before our application starts to serve requests.

It was a common practice to call the functions that we wanted to get executed through GlobalSettings, but that was not recommended.

Categories: Java

Rapid prototyping with Vue.js

codecentric Blog - Thu, 04-Jan-18 23:57

When I started at codecentric, I had no clue about frontend frameworks. Sure, I knew my HTML and CSS and I did some dynamic pages with PHP, but who didn’t? The first frontend-only framework I seriously worked with was AngularJS. I had a hard time getting into it, which was mostly based on the fact that it was ill-used in our project setup. Instead of separate modules for different parts of the software, we had one giant controller that only got more and more code branches for all the little specialities that were necessary for our business cases.

After a while, our team broke up this massive pile of code. I was eager to help and got a better understanding of JavaScript and AngularJS every day. Today I am pretty familiar with AngularJS projects. Although there is one thing that’s always bothered me. Setting up a small Angular project, for example if you want to quickly try out an idea, can be pretty tedious.
I took a look at other frameworks (Angular2, React) in hope that they would be more easy to start a project with, but there you mostly start with an npm/webpack/whatever setup, which is often just totally overweight.

Then I came across Vue. And I really like how lightweight it can be. In this tutorial, I want to show you how quickly you can set up a dynamic webpage, even with REST functionality. A little bit of basic JavaScript knowledge is helpful here. You should also be familiar with the usage of your browser’s developer tools.

If you want to program along, create an index.html and paste this snippet. In the snippet I added some css styling, so the whole thing looks a little bit nicer.

Let’s start with a simple form:


  
    Zip:
    
    
  


  City
  Matching City:
  Insert zip to display matching city

This should render you the following form:

Rendered form

The form should take a valid (in this case German) ZIP and show the matching city.
Now let’s init Vue.js. Add a link to vue.js to the header:


   

Then add a script snippet before the closing html tag where you init Vue:


    new Vue({
        el: '#zip-loader',
        data: {
            city: 'Insert zip to display matching city'
        }
    });

We don’t have an Element ‘#zip-loader’ yet, so create a div around the existing form:

Replace the text ‘Insert zip to display matching city’ with {{ city }}, so that it looks like this:

Matching City: {{ city }}

Reload the file. It should look the same. Only the text is now taken out of the data part of the Vue instance we created. Try changing the text in the city field. It should change in your form. If something’s wrong, check your browser console for errors. Vue is very verbose and it’s often easy to spot the mistakes.

Let’s register the user’s input. Add a ZIP field to the data section of your vue instance and set it to be an empty string:

data: {
  zip: '',
  ..
}

Bind the new field to the input field in the form. Now everything the users enter here will be directly bound to the ZIP field in the data section of our Vue instance.

  

Now let’s add a method that is called when a letter is entered:

  

Add a methods block in your Vue instance and define the method ‘parseZip’ in it. Let’s just log the value of the ZIP field.

  methods:{ 
    parseZip: function(){
    console.log(this.zip);
  }
}

Now if you enter something in the input field, your browser should log it to the console. By the way, this references your Vue instance.

Now that we get user input, we need to do something with it. We want to load a matching city for an entered ZIP. Since we don’t have a backend, we use a public API for this. http://api.zippopotam.us/ offers a very easy to use API. If you call http://api.zippopotam.us/de/42697 (the ZIP of the city Solingen in Germany), you get a nice JSON object that holds all the necessary information:

{
  "post code": "42697",
  "country": "Germany",
  "country abbreviation": "DE",
  "places": [{
    "place name": "Solingen",
    "longitude": "51.1611",
    "state": "Nordrhein-Westfalen",
    "state abbreviation": "NW",
    "latitude": "05122"
  }]
}

Vue cannot make REST calls. So we need another library for this. I use axios, but you can use any REST library you like. To embed it, just add the JavaScript source to the header:


      

This enables you to make a GET call in the parseZip method:

parseZip: function(){
  axios.get('http://api.zippopotam.us/de/42697')
  .then(function(response){
  console.log(response.data);
  })
}

Instead of logging the content of the ZIP field, we now make a REST call every time the user enters a key. The resulting data is then logged to the browser console.

Now modify the REST URL to take the ZIP from the data object of our Vue instance:

  axios.get(`http://api.zippopotam.us/de/${this.zip}`)

Note that I changed the single quotes to backticks here, so I can use template strings.

Since ZIP codes in Germany are generally 5 digits long, add a safeguard around the method, so that the API is not called with a definitely invalid ZIP. Also, change the log function to log the retrieved city. Take a look at the JSON object again, to better understand the syntax I used here.

if (this.zip.length === 5) {
  axios.get(`http://api.zippopotam.us/de/${this.zip}`).then(function(response) {
  console.log(response.data.places[0]['place name']);
  })
}

To show the retrieved city on the website, just assign it to the data object. Note: We need to assign the Vue instance to a variable first, because the callback function of the REST call creates a new scope where this doesn’t reference the Vue instance any more.

const myApp = this;
if (this.zip.length === 5) {
  axios.get(`http://api.zippopotam.us/de/${this.zip}`)
  .then(function (response) {
  myApp.city = response.data.places[0]['place name'];
  })
}

If you now enter a valid ZIP into the input form, it should show the name of the matching city.

Now our basic functionality is done. Let’s finish up with a little error handling and a loading message.

To show an error message, add a catch block to the get method.

axios.get(`http://api.zippopotam.us/de/${this.zip}`)
.then(function (response) {
  myApp.city = response.data.places[0]['place name'];
})
.catch(function(){
  myApp.city = 'Not a valid zip code';
})

To show a loading message, we need a little additional CSS:


…
.visible {
  display: inline;
}
…

Add a loading flag to the data section:

data: {
           …
            loading: false
        }

Set the flag to true before the GET call:

…
myApp.loading = true; 
axios.get(`http://api.zippopotam.us/de/${this.zip}`)
…

And set it to false when loading is done:

.then(function (response) {
  myApp.city = response.data.places[0]['place name'];
  myApp.loading = false;
})
.catch(function () {
  myApp.city = 'Not a valid zip code';
  myApp.loading = false;
})

Now all there is left is changing the CSS class of the Loading... text according to the flag.

Loading...

That’s it. We’re done. We created a dynamic, RESTful web page without any build or packaging tools. This shows why Vue is a great framework if you want to try out something very quick.

You can look up the final code at https://github.com/Guysbert/vue-rapid-protoyping or play with it in this codepen.

See the Pen Rapid protoyping with vue by Andreas Houben (@ahouben) on CodePen.

The post Rapid prototyping with Vue.js appeared first on codecentric AG Blog.

Categories: Agile, Java, TDD & BDD

Playing Around With Spring Bean Configuration

Javalobby Syndicated Feed - Thu, 04-Jan-18 22:01

In this tutorial, we will have a look at something more basic on the Spring spectrum — beans. But, as with most things, the fundamentals can sometimes be forgotten, and bean creation is something that I personally have not looked at properly since switching from XML to Java configuration.

The creation of beans is pretty important to the use of Spring (probably more like very important), allowing us to have Java classes that live within the application context that can be used within other beans/classes without constantly creating new instances every time we need to use one of their methods.

Categories: Java

This Week in Spring: The 7th Anniversary Edition

Javalobby Syndicated Feed - Thu, 04-Jan-18 10:01

Hi, Spring fans! Welcome to another installment of This Week in Spring! I hope you had a wonderful, safe, and fruitful new year celebration.

This is the first roundup of the new year and so it is also the 7th year anniversary of my starting this column. Every Tuesday, without fail (come holiday, sick-day, flights, or frights!), since the first week of January 2011, I’ve put together this roundup. It has been, and continues to be, an honor. As usual, I’m always happy to have feedback and suggestions from you, the most amazing community ever! Don’t hesitate to reach me on Twitter (@starbuxman).

Categories: Java

Java Quiz 8: Upcasting and Downcasting Objects

Javalobby Syndicated Feed - Thu, 04-Jan-18 04:01

Before we start with this week's quiz, here is the answer to Java Quiz 7: Using Unary Operators.

x++ and ++y are very similar, but not exactly the same. Both increment the value of the variable by one, but ++y increments the value by one before the current expression is evaluated, while x++ increments the value of the variable by one after the expression is evaluated. The statement MyClass mc = new MyClass(3, 3); creates the object mc. By using the statement this.x = x++; the value of x remains x, while the statement this.y = ++y; increments the value of y by one. So, y = 4. The statement System.out.println(mc.method(mc)); invokes the method. The statement mc.x += 9; increments the value of x by 9. So, x = 3 + 9 = 12. The statement mc.y += 2; increments the value of y by 2. So, y = 4 + 2 = 6. The method returns mc.x + mc.y = 12 + 6 = 18.

Categories: Java

Continuous Validation for Security Configurations

codecentric Blog - Thu, 04-Jan-18 02:00

Testing integration with a component that has a completely separate life cycle apart from your application is hard. Think about a database system version upgrade. In more cases than one, it has caused a decision to skip automation entirely and rely on manual testing instead. An IAM solution is just like that. It’s configuration-heavy and it is often managed outside of the scope of your team. However, end-to-end testing definitely forces us to consider how we functionally test our security.

Last year, Keycloak became popular (marked assess by TechRadar) as an open source IAM solution and it offers a wide range of APIs. My colleagues already wrote some nice articles. I wanted to explore the opportunities of using Keycloak for our CI to improve testability in our IAM integration.

With Keycloak you are able to continuously test IAM integration in your E2E test suite.

Recently I discovered Keycloak as an Identity and Access Management (IAM) candidate for our Gareth.io platform and another product which is still in incubation. So far, I am pleased with what I have found. The ease of integration via its endpoints is what makes it an especially interesting candidate. Additionally I found a good opportunity to use Keycloak as an E2E test candidate.

Keycloak is developed and promoted by Red Hat. The project pages are located at http://keycloak.jboss.org, the sources can be found in GitHub. The product is completely written in Java and extensively uses Red Hat’s Java Stack. WildFly is used as the default application server and Wildfly’s clustering and high availability functions are also used. Read a nice introduction from my colleague here.

Step 1. Additions to the infrastructure

There are a number of options to configure Keycloak. There is an administrative UI, a config file (keycloak.xml), a CLI, and everything is configurable using the REST interface. All applications living in the same logical domain are in the same Realm. A realm contains the functional administration options (eg. allowed roles, user profile fields, authentication providers, etc.).

To make it testable, I used the jboss/keycloak Docker image to get a basic running Keycloak instance. I have a CI job that creates a basic Keycloak, specific to my project. I use it to configure my realm and roles. It has its own lifecycle and is managed by a separate pipeline. There is a base image which contains basic Keycloak realm configuration. Based on my Keycloak base image I build my production Keycloak (with enriched configuration) and multiple configuration variants for testing Keycloak in my CI pipeline.  

Step 2. Add Keycloak to the test project

Next, we need to add a Keycloak client to our test infrastructure. I use Cucumber (Java variant) to drive my acceptance tests. I added the official Keycloak client jar  and RESTEasy libraries.

In order to connect to it, you can initiate an instance of the client like this:

Keycloak integration code example

 

 

 

 

 


Now let’s influence Keycloak with our newly bootstrapped library. We first define a Cucumber step and then create an implementation:

Cucumber test

 

And the corresponding Java implementation for our step. We will create a new user within the realm of the tested application and assign it an administrator role. Because we instantly want to use this user in our test we need to mark it as enable.

Cucumber test

 

Now this is just one example of things you can do in your CI with keycloak. I personally am not the biggest fan of testing too many non-functionals in your E2E tests. Functionally you can thoroughly test your registration and sign-in functionality. This is probably not where the main business value is delivered, but it is the start of the user experience in many applications. So we should make sure to capture regression in an early stage of delivery. Furthermore, there are some really nice non-functional cases that used to be hard or required a lot of manual testing which is now possible automagically.

Server side session invalidation

In a modern web application security tokens can be distributed across apps, single-page application frontends and backend applications. Testing this is cumbersome and intrinsically complicated. With the Keycloak client you are now able to influence one or more realms. A very nice feature is ‘RealmResource.logoutAll()’ which invalidates all running sessions on the server. Afterwards you can verify that clients behave accordingly. But there are plenty more.

Wrapping up

We have seen an example on how to integrate Keycloak in your acceptance testing suite. Because we use Docker it’s easily integrated in popular CI tools like Gitlab, Jenkins or CircleCI. Based on what I have seen so far, everything you can do in the Keycloak administrative interface is administrable over REST. Next to this interface there is also the possibility to use shell scripts for administrative purposes. For ultimate flexibility Keycloak is easily and quickly booted in a container so one could even swap out security providers.

My final advice is to keep your Cucumber steps generic. Once created they can be reused  across multiple projects and teams.

 

Handy sources and follow-up work

Keycloak website: https://www.thoughtworks.com/radar/platforms/keycloak

Dieter Dirkes’ introduction: https://blog.codecentric.de/2016/06/accessmanagement-mit-keycloak/

Jannik Hüls: https://blog.codecentric.de/2016/08/single-sign-mit-keycloak-als-openid-connect-provider/

 

The post Continuous Validation for Security Configurations appeared first on codecentric AG Blog.

Categories: Agile, Java, TDD & BDD

Writing Custom AssertJ Assertions [Snippet]

Javalobby Syndicated Feed - Thu, 04-Jan-18 01:01

AssertJ is an alternative matching library to the widely used Hamcrest matchers. For my own projects, I, in fact, have changed to solely use AssertJ — I just find the fluid interfaces and extensibility quite appealing.

You can write custom assertions as follows.

Categories: Java

Java Concurrency in Depth (Part 2)

Javalobby Syndicated Feed - Wed, 03-Jan-18 22:01

In the first part of this series, Java Concurrency in Depth (Part 1), I discussed the internals of Java's synchronization primitives (synchronized, volatile, and atmoic classes) and the pros and cons of each of them.

In this article, I will discuss other high-level locks that are built on top of volatile, atomic classes and Compare-And-Swap.

Categories: Java

Optional... What Else?

Javalobby Syndicated Feed - Wed, 03-Jan-18 14:01

Optional is in some ways, the Java implementation of the Maybe monad. Don’t get scared by the ‘M’ word. It is simply an encapsulation to handle a specific case of a type — in this case, the possibility of a null value. Just consider it a wrapper to force the user to check if the value is present or not.

When using an Optional in a declarative way, we are able to execute a map function on it. The lambda supplied with the map will only be executed if the Optional is filled with a value.

Categories: Java

Single-Responsibility Principle Done Right

Javalobby Syndicated Feed - Wed, 03-Jan-18 10:01

I am a big fan of the SOLID programming principles by Robert C. Martin. In my opinion, Uncle Bob did a great job when he first defined them in his books. In particular, I thought that the Single-Responsibility Principle was one of the most powerful among these principles, yet one of the most misleading. Its definition does not give any rigorous detail on how to apply it. Every developer is left to their own experiences and knowledge to define what a responsibility is. Well, maybe I found a way to standardize the application of this principle during the development process. Let me explain how.

The Single-Responsibility Principle

As is normal for all the big stories, I think it is better to start from the beginning. In 2006, Robert C. Marting, a.k.a. Uncle Bob, collected in the book Agile Principles, Patterns, And Practices in C# a series of articles that represent the basis of clean programming — the principles are also known as SOLID. Each letter of the word SOLID refers to a programming principle:

Categories: Java

dotenv for Java and the JVM

Javalobby Syndicated Feed - Wed, 03-Jan-18 04:01

When working within the context of a modern microservice architecture, one often encounters services written in a variety of languages using a variety of frameworks. There are numerous benefits to microservice architectures, however, configuring each service can be quite complex. Each framework may offer their own configuration method, e.g. property files, YAML, JSON, etc. As the number of microservices piles up, this quickly becomes a DevOps nightmare.

To avoid this problem, we need a single method for configuration. Fortunately, there is one, dotenv, and most languages already offer a port. dotenv is a library originating from the Ruby community. It offers a simple, consistent, 12-factor compliant method to configure an application using environment variables.

Categories: Java

Transactional Exception Handling in CDI [Snippet]

Javalobby Syndicated Feed - Wed, 03-Jan-18 01:01
In Java EE, exceptions that are raised during the execution of a transactional business method cause the transaction to roll back. However, this is only the case for system exceptions, that is, runtime exceptions, which are not declared in the method signature.

For application exceptions, that is, checked exceptions, or any exception annotated with @ApplicationException, the transaction is not automatically rolled back. This sometimes causes confusion among enterprise developers.

For EJB business methods, the transactions can be forced to roll back on application exceptions as well by specifying @ApplicationException(rollback = true). However, this annotation is only considered if the managed bean in an EJB.

Categories: Java

Significant Software Development Developments of 2017

Javalobby Syndicated Feed - Tue, 02-Jan-18 22:01

This post is my personal and opinionated assessment of some of the most significant developments related to software development in 2017. This is my eleventh year for this annual post and my previous years' assessments are available for 2016, 2015, 2014, 2013, 2012, 2011, 2010, 2009, 2008, and 2007. As with these previous years' assessments, this assessment of 2017's major developments in software development are obviously biased, opinionated, and limited to my perspective.

I think it important to re-emphasize that although this is an opinion-heavy post, the opinions are not on whether a particular language, framework, or tool is "best" or "worst." Rather, the opinions come in when deciding which of these frameworks, languages, or tools had the biggest developments of the year.

Categories: Java

Spring, Spring Boot, and Component Scan

Javalobby Syndicated Feed - Tue, 02-Jan-18 14:01

This guide will help you understand the most important concept in Spring — Component Scan. Spring Boot does some magic around Component Scan. Let’s understand that in this article.

You Will Learn

  • What is Component Scan?
  • Why is Component Scan important?
  • Which packages does Spring Boot scan automatically?
  • How do you define Component Scan with Spring Boot?
  • How do you resolve problems involving Component Scan?

@ComponentScan

If you understand Component Scan, you understand Spring.

Categories: Java

Currying Functions in Scala

Javalobby Syndicated Feed - Tue, 02-Jan-18 13:01

Currying is named after Haskell Curry, an American mathematician. He is known for his work in combinatory logic.

Currying is a means of transforming a function that takes more than one argument into a chain of calls to functions, each of which takes a single argument.

Categories: Java

Handling RxJava Observables in a Web UI

Javalobby Syndicated Feed - Tue, 02-Jan-18 13:00

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

Thread Slivers eBook at Amazon

Syndicate content