Spring Boot Security and H2 console

The configuration shown below should be used only in a development environment and not in production.

After enabling Spring Security in your Spring Boot application, you will not be able to access the H2 database console anymore.

With its default settings under Spring Boot, Spring Security will block access to H2 database console.

To be able to access to the H2 database console under Spring Security you need to change these four things:

  • Enable h2 console in your application.properties file

  • Allow all access to the URL path /console/*.

  • Disable CRSF (Cross-Site Request Forgery). By default, Spring Security will protect against CRSF attacks.

  • Since the H2 database console runs inside a frame, you need to disable this in Spring Security.

So, the very, very simple security configuration that allows you to access h2-console should look like:

 

After applying these changes and trying to access your h2-console

http://localhost:8080/h2-console/

You should see h2-console login page:

 

Simple Jersey example with Intellij IDEA Ultimate and Tomcat

Jersey

RESTful Web Services in Java.

Jersey is a reference implementation of the JAX-RS 2.0 API. Jersey provides it’s own API that extends the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and client development.

In this example I will be using:

  • IntelliJ Idea Ultimate 2016.2
  • Jersey 2.23.2 (latest stable release of Jersey as of time of writing)
  • JDK 8
  • Tomcat 8.0.35

Create new project

To create a new project, open up the New Project dialog in IntelliJ. In the left menu, select Java Enterprise. To the right, select Web Application and ensure that Create web.xml is checked.

newproject

 

Add Maven support

To add Maven to your project, right-click on your project’s name in the Project sidebar and select Add Framework Support.

In the Add Frameworks Support, select Maven.

Once this is done, the pom.xml file will open in the editor. You will need to enter at least a groupId, usually your package name. At this point, it is helpful to enable auto-importing for library dependencies.

maven

Add Jersey dependencies to the Maven pom.xml file

 

Create a Resource

Inside of the src/main/java directory, create a new package matching your groupId.

And then create a simple java class – MyResource in my case.

Modify index.jsp file by adding a link to the Jersey resource

 

Check if Tomcat is configured properly.

tomcat-configuration

tomcat-deployment

 

Configure your servlet

Modify your web.xml file

 

Before we run our application, first we need to add Jersey jars to the /WEB-INF/lib directory

add-artifacts

After selecting all jars right click and choose “Put into /WEB-INF/lib

Run your Application

jersey-resource
got-it

 

DONE!

 

 

Git for an absolute beginners

Before I started using Git on my personal and then on commercial projects, I was using for many years  Subversion – svn in short. SVN is still very popular but Git earned its strong position as well by being used in large and small projects for more than 10 years already.

Installing Git

The official website of Git has detailed information about installing on Linux, Mac, or Windows. In this case, I will be using Ubuntu 16.04 for demonstration purposes, and installing git in Linux (Ubuntu) is simple as typing:

Before we dive into configuration and will start using Git a bit of terminology introduction is necessary.

Here’s the git terminology:

  • master – the repository’s main branch. Depending on the workflow it is the one people work on or the one where the integration happens
  • clone – copies an existing git repository, normally from some remote location to your local environment.
  • commit – submitting files to the repository (the local one); in other VCS it is often referred to as “checkin”
  • fetch or pull – is like “update” or “get latest” in other VCS. The difference between fetch and pull is that pull combines both, fetching the latest code from a remote repo as well as performs the merging.
  • push – is used to submit the code to a remote repository
  • remote – these are “remote” locations of your repository, normally on some central server.
  • SHA – every commit or node in the Git tree is identified by a unique SHA key. You can use them in various commands in order to manipulate a specific node.
  • head – is a reference to the node to which our working space of the repository currently points.
  • branch – is just like in other VCS with the difference that a branch in Git is actually nothing more special than a particular label on a given node. It is not a physical copy of the files as in other popular VCS.

Initial Configuration

We need to configure our name and email. You can do it as follows, replacing the values with your own name and email.

It is important to note that if you do not set your name and email, certain default values will be used.

Create a new Git Repository

Before starting, let’s create a new directory where the git repository will be created and ‘move’ into it.

Now we can initialize our first git repository.

To check the status of our repository git status command can be used.

Create and commit a new file

The next step is to create a new file and add some content to it.

Let’s check what happen in our git repository.

To “register” the file for committing we need to add it to git using:

And again, let’s check what happen in our git repository.

 

We can now commit it to the repository.

Let’s add another file to the project.

 

Create a (feature) branch

Branching and merging is what makes Git so powerful and for what it has been optimised, being a distributed version control system (VCS). Indeed, feature branches are quite popular to be used with Git. Feature branches are created for every new kind of functionality you’re going to add to your system and they have usually deleted afterwards once the feature is merged back into the main integration branch (normally the master branch). The advantage is that you can experiment with new functionality in a separate, isolated “playground” and quickly switch back and forth to the original “master” branch when needed. Moreover, it can be easily discarded again (in case it is not needed) by simply dropping the feature branch. But let’s get started and create the new feature branch:

To see a list of all branches we need to use git branch command.

A star next to master branch indicates that this is a current branch.

Let’s switch to this newly created branch and modify one of the files.

And then add and commit it to the branch.

 

Ok, it’s time to complicate it and cause some conflicts. To do this we need to switch to ‘master’ branch and modify the blogpost.txt file.

 

If you need to commit a file that was already added to the git repository you can use command ‘commit -a -m’

Merge and resolve conflicts

The next step would be to merge our feature branch back into ‘master’. This is done by using the merge command.

Edit file and resolve conflict and commit changes to the branch.

 

Rollback

What if we want to undo everything back to the state before the commit?

First, we need to get SHA identifiers (unique ‘id’ for each node in git tree).

 

and then move back in time to the desired node/commit

 

 

And that’s it. It is everything that is needed to start using git. I have covered here only simple commands. For more advanced commands and explanations I highly recommend reading this book: Pro GIT.

Spring – Conditional annotation

Spring 4 has introduced a new annotation @Conditional. It is used to develop an “If-Then-Else” type of conditional checking for bean registration. Let us see how we can use @Conditional annotation to check a property value is dev or prod from environment. For learning we will use Java based configurations in this example.

Create Project Domain class with id, name and duration properties with getters only as shown below.

Create Utility classes to represent in-memory Databases. For simplicity, we are not interacting with Databases. DevDatabaseUtil class represents DEV database and ProductionDatabaseUtil class represents PROD database with some data.

Create a ProjectDAO class to represent DAO Layer.

Now it’s time to implement Conditional checking by using@Conditional annotation. Both condition checking classes implements Spring’s Condition interface matches() method. Both Conditional classes checks for “database.name” from environment. If this values is “dev”, then DevDataSourceCondition’s matches() method returns true. Otherwise false. In the same way, if this property value is “prod”, then ProdDataSourceCondition’s matches() method returns true. Otherwise false.

Create Spring’s Java-based configuration classes

Now it’s time to write JUnits to test Spring’s @Conditional classes.

 

DI – Configuring Beans

Component annotations

Spring creates beans for classes with auto component scanning features by using @Component. @Component annotation is not only one you can use for creating beans, there are others more ‘specialized’ annotations.

  • @Controller – Indicates a controller component in the presentation layer
  • @Service – Indicates a Service component in the business layer
  • @Repository – Indicates DAO component in the persistence layer

So, which one to use? It’s really doesn’t matter. Take a look at the source code one of those annotations:

You will notice that all @Repository,@Service or @Controller are annotated with @Component. So, can we use just @Component for all the components for auto scanning? Yes, you can, and Spring will auto scan all your components with @Component annotated.

It’s working fine, but not a good practice, for readability, you should always declare @Repository,@Service or @Controller for a specified layer to make your code more easier to read.

Configuration classes

Let’s assume that our Service classes (SmsService, TweetService, MailService) are part of some third party JAR and we won’t be able to annotate those with @Component. In this case we can use Java configuration classes. To make our application working again we need to create some config class where we will add our service classes to be able to be scanned by Spring.

Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context. The name of the methods become the names
of the beans by default.

DI – Two beans implementing same inteface

How to inject the right one?

To see what happens lets annotate with @Component our TweetService class.

Trying to run the application you’ll get an error:

Spring, when trying to find a suitable bean for injecting to the messageService variable, finds two beans – the instances of both TweetService and SmsService.

Let’s try to fix it. One of few ways to do it is, to specify a name in @Resource annotation.

Spring will then be able to inject the exact bean without any error.

Another alternative will be to give a name to the bean to match the resource name.

Yet another option to tell Spring which bean to inject is to use @Primary annotation.

The application should still run fine.

A more powerful (it not only works on setters, but on any method, including the constructors) but still very similar to @Resource is @Autowired annotation.

However, @Autowired does not take the name element. Instead, we need to use @Qualifier along with @Autowired.

By default, the qualifier of a bean will be same as its name.

 

Spring also has @Inject , which is synonymous to @Autowired. It’s part of the Java CDI JSR-300 standard, and so Spring thought to support it. What is the difference between @Inject and @Autowired?

The short answer: There is no different and can be used interchangeably.

In more detail @Inject is part of the Java CDI (Contexts and Dependency Injection) standard introduced in Java EE 6 (JSR-300). Spring has chosen to support using @Inject synonymously with their own @Autowired annotation.@Autowired is Spring’s own annotation. In a Spring application, the two annotations works the same way as Spring has decided to support some JSR-300 annotations in addition to their own.

 

DI – Dependency injection by name and type

@Resource by default the name of the bean will be its class name in camelCase. That means, the SmsService instance, which will be put in the application context as a result of being annotated with @Component, will be named as smsService. To change the default name, we can supply a value element to @Component:

This behavior is called dependency injection by name.

Now I show you an example of DI by name:

But, if we remove a name parameter from @Resource annotation and then we’ll try to run our example, everything should work as before. Why?

At the start of application Spring first try to find a bean with messageService name and will fail, next step will be to try to find a bean of the same type, and in our example as SmsService is a subtype of MessageService and as a result of successfully running application, we should get:

Your message was sent

And in the console log:

 

Hello, Programmer’s curiosity

An example of very simple Spring application that will be extended in next posts to demonstrate Spring framework and DI (dependency injection).

For all examples I’ll be using IntelliJ Idea Ultimate, an ide of my choice for at last 3 years, I love it’s features and productivity speedup that comes with it.

Creating a new Spring project

There are many ways to create a new Spring project. You can create it from scratch or use Spring Initializr plugin for IntelliJ Idea or do it via web Spring Initializr (it creates a zip file, which you can download, unzip and import in your IDE).

SpringInitializr

Next step is to enter few metadata for our project:

Name
It’s the name of the project, e.g. spring-for-blog-demo
Type
It’s the build tool selection to help us compile and package our project. There are a couple of options: Maven and Gradle. I prefer to go with Maven, because of its wide adoption, unless there is a specific need for Gradle.
Packaging
You’ll find two options here – JAR and WAR.
The executable of our application. That JAR or WAR can run standalone, with the standard java -jar command.
Choose JAR packaging here, unless you are using JSP, which needs WAR packaging.
Java version
Our choice is 1.8 here.
Group and Artifact
Group and Artifact uniquely identify a project. Group will identify your project uniquely across all projects, what means that has to be at least as a domain name you control (no problem if you don’t own a domain – just use some name which you feel will be unique), and you can create as many subgroups as you want, e.g. com.programmerscuriosityArtifact uniquely identifies the project inside the group. It is the name of the jar without version. You can choose whatever name you want with lowercase letters and no strange symbols e.g. springforblogdemo.
Version
If you distribute it then you can choose any typical version with numbers and dots (1.0, 1.1, 1.0.1, …). Don’t use dates as they are usually associated with SNAPSHOT (nightly) builds. For our purpose just leave it untouched.
Description
This is a one line description of the project.
Package
This will be the name of the root package of your application. The common practice for naming it is to join the group and the artifact in some way, e.g. com.programmerscuriosity.springblogdemo.
Remember that “-” isn’t allowed here.

NewProject_metadata

Boot version
This is the version of Spring Boot to use. Normally we’d choose the latest stable release.
Dependencies
This section asks us to choose the dependencies needed. Whatever we choose here will go into the configuration file of the build tool. The build tool will then automatically fetch the needed JARs and put those in the classpath. So, choose just Web for now, and more dependencies can easily be added into the configuration file later.

NewProject_dependencies

Press Next and Finish to create the project in your workspace.

NewProject_structure_and_pom

Running our application at this stage won’t show any results apart from getting an error page (not even defined by us).

WhiteLabelPage

So, lets create a simple controller class and try to display at least simple Hello message.

Create a new package, e.g. com.programmerscuriosity.springforblogdemo.controllers. Inside that package, create a new class, HelloController:

Start your server and type http://localhost:8080/hello in your browser.

hello_programmers_curiosity

And that’s it. We’ve got our base project for further posts about Spring DI ready and running.

 

HTTP Request Methods: GET and POST

What is HTTP?

The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers.

HTTP works as a request-response protocol between a client and server.

A web browser may be the client, and an application on a computer that hosts a web site may be the server.

HTTP Methods:

Two commonly used methods for a request-response between a client and server are: GET and POST.

The GET method

The GET method is used to retrieve information from a specified URI and is assumed to be a safe, repeatable operation by browsers, caches and other HTTP aware components. This means that the operation must have no side effects and GET requests can be re-issued without worrying about the consequences.

One downside of GET requests is that they can only supply data in the form of parameters encoded in the URI (known as a Query String) or as cookies in the cookie request header. Therefore, GET cannot be used for uploading files or other operations that require large amounts of data to be sent to the server.

The POST method

The POST method is used for operations that have side effects and cannot be safely repeated. For example, transferring money from one bank account to another has side effects and should not be repeated without explicit approval by the user.

The POST request message has a content body that is normally used to send parameters and data. Unlike using the request URI or cookies, there is no upper limit on the amount of data that can be sent and POST must be used if files or other variable length data has to be sent to the server.

Compare GET vs. POST

The following table compares the two HTTP methods: GET and POST.

GET POST
BACK button/Reload Harmless Data will be re-submitted (the browser should alert the user that the data are about to be re-submitted)
Bookmarked Can be bookmarked Cannot be bookmarked
Cached Can be cached Not cached
Encoding type application/x-www-form-urlencoded application/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data
History Parameters remain in browser history Parameters are not saved in browser history
Restrictions on data length Yes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters) No restrictions
Restrictions on data type Only ASCII characters allowed No restrictions. Binary data is also allowed
Security GET is less secure compared to POST because data sent is part of the URL

Never use GET when sending passwords or other sensitive information!

POST is a little safer than GET because the parameters are not stored in browser history or in web server logs
Visibility Data is visible to everyone in the URL Data is not displayed in the URL

Other HTTP Request Methods

The following table lists some other HTTP request methods:

Method Description
HEAD Same as GET but returns only HTTP headers and no document body
PUT Uploads a representation of the specified URI
DELETE Deletes the specified resource
OPTIONS Returns the HTTP methods that the server supports
CONNECT Converts the request connection to a transparent TCP/IP tunnel