Development, Java, Spring

Using Spring Data to persist a Set of Enums in a Many-To-Many relationship

Usually, when we write a Many-To-Many relationship it is between 2 entities. Sometimes, it could happen that we have an entity which has a field which is a set of enum. In this case, we need to approach the problem differently and Spring comes to help.

Let’s see an example where we have two classes: Person and Skill (e.g. swimming, running, etc).

Many-To-Many between entities example

The following code shows what the situation is when Person and Skill are both entities.

public class Person {
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;
  @ManyToMany(fetch = FetchType.LAZY)
  @JoinTable(name = "person_skill", joinColumns = {
            @JoinColumn(name = "person_id")}, inverseJoinColumns = {
            @JoinColumn(name = "skill_id")})
  private Set<Skill> skillSet;

public class Skill {
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;

To use this mapping, you would have 3 tables. You can create them with the following SQL code.

CREATE TABLE `person` (
  `name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`));

CREATE TABLE `skill` (
  `name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`));

CREATE TABLE `person_skill` (
  `person_id` BIGINT(20) NOT NULL,
  `skill_id` BIGINT(20) NOT NULL,
  PRIMARY KEY (`person_id`, `skill_id`),
  INDEX `skill_fk_idx` (`skill_id` ASC),
  CONSTRAINT `person_fk`
    FOREIGN KEY (`person_id`)
    REFERENCES `person` (`id`)
  CONSTRAINT `skill_fk`
    FOREIGN KEY (`skill_id`)
    REFERENCES `skill` (`id`)

Many-To-Many between entity and enum example

The following code shows what the situation is when Person is an entity and Skill is an enum.

public class Person { 
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id; 
  private String name; 
  @ElementCollection(targetClass = Skill.class)
  @CollectionTable(name = "person_skill",
            joinColumns = @JoinColumn(name = "person_id"))
  @Column(name = "skill_name")
  private Set<Skill> skillSet;

public enum Skill {

To use this mapping, you would have only 2 tables, because Skill is not an entity and would not have its own table. You can create them with the following SQL code.

CREATE TABLE `person` (
  `name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`));

CREATE TABLE `person_skill` (
  `person_id` BIGINT(20) NOT NULL,
  `skill_name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`person_id`, `skill_name`),
  CONSTRAINT `person_fk`
    FOREIGN KEY (`person_id`)
    REFERENCES `person` (`id`)

As you can see here, you don’t have the table skill because Skill is not an entity but only an enum; you only have to create the table which represents the relationship between Person and Skill. Furthermore, since we added the annotation @Enumerated(EnumType.STRING) Spring Data will save the name of the entity in the database (look, we put a VARCHAR column). If you prefer, you could use EnumType.ORDINAL and Spring Data will save the ordinal value of the entity (1,2,3,etc..), so change the column to accept a numeric value.

That’s it!

sysadmin, tools, Windows

MobaXterm – Enhanced SSH client for Windows

I’ve always struggled myself each time I had to use SSH on Windows (yes, at least half of the time I use it, I like it). Just few months ago Windows released the Bash Ubuntu integration, which is very well integrated with the Windows environment and it’s a very cool feature, even if it is still a beta!

Anyway, since I was always looking for a better alternative than PuTTY, I finally found an alternative which is extremely worth to be mentioned, MobaXterm.

It has a very cool list of features and has both a free and a professional editions.

It is a lot more than only a featured SSH client, so, really,  give it a look, it’s really worth it!

Thank you MobaXterm!

Android, Development

Android Contextual Action Bar

In this post you will learn how to implement a Contextual Action Bar (CAB) which will be useful to do actions on multiple items you have selected in a RecyclerView.

The Contextual Action Mode represents a contextual mode of the user interface and focuses user interaction toward performing contextual actions. In the case of a RecyclerView which shows a list of item, Contextual Action Mode is triggered after a long press on one of this items: this causes the Contextual Action Bar to appear at the top of the screen so then the user can interact with its actions.

Let’s follow these steps!

Initial setup

First of all, create a RecyclerView and its adapter in the usual way you do it. Here in this example I will use a RecyclerView which shows Authentication items (it is a class I made for a project, it doesn’t matter for the purpose of the example, use whatever you want, and change the names accordingly).

Theme changes

Open your styles.xml file and add the following lines:

<!--  It should be true otherwise action mode will not overlay toolbar -->
       <item name="windowActionModeOverlay">true</item>
       <!--  For Custom Action Mode Background Color/Drawable -->
       <item name="actionModeBackground">@color/colorAccent</item>

Comments should be self-explanatory.

Menu file

We need a menu file which contains the available actions for that RecyclerView. Let’s create a file into the res/menu directory like the following:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android=""

        app:showAsAction="always" />


We added a delete action that will be shown on the CAB.

Adapter changes

Our adapter we created in the first step needs to be able to keep trace of the elements we select. To do this, let’s modify our adapter and create a new field

private final SparseBooleanArray selectedItemsIds;

and initialize it in our constructor

selectedItemsIds = new SparseBooleanArray();

Now, let’s create an Interface which will be useful for all the Adapters which need the CAB, and make our Adapter implements it. Please note this is a generic interface, so adapt it to the model you are displaying in your adapter.

public interface ActionModeAdapterCallbacks<T> {

    void toggleSelection(int position);

    void clearSelections();

    int getSelectedCount();

    List<T> getSelectedItems();

This is what the implementation should look like:

public void toggleSelection(final int position) {
    if (selectedItemsIds.get(position)) {
    } else {
        selectedItemsIds.put(position, true);

public void clearSelections() {

public int getSelectedCount() {
    return selectedItemsIds.size();

public List<Authentication> getSelectedItems() {
    final List<Authentication> selectedItemList = new LinkedList<>();
    for (int i = 0; i < selectedItemsIds.size(); i++) {
    return selectedItemList;

Now, we also need the Adapter to change the view state when an item gets selected to show the user a visual feedback. To do this we can use a StateListDrawable and in the onBindViewHolder() method add this line.


Create a new xml file inside the res/drawable directory:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
    <item android:drawable="@color/colorPrimaryDark" android:state_activated="true" />
    <item android:drawable="@android:color/transparent" />

and assign it to the root view element of the layout file which represents your adapter’s row item:


Doing so, each time an item is selected or deselected, the adapter will change its color accordingly.

Fragment/Activity changes

Now, we need to make our Fragment/Activity class aware that we can trigger the Contextual Action Mode. To do so, let’s create an interface and call it ActionModeViewCallbacks.

public interface ActionModeViewCallbacks {

    void onListItemSelect(final int position);

    void onDestroyActionMode();


This interface has 2 methods:

  • onListItemSelect(final int position): to be used after a long click on an item to trigger the Action Mode (or after a single click on an item, if Action Mode was already triggered, to select this new item, too);
  • onDestroyActionMode(): reset actionMode variable to null;

Now, let’s create another interface which extends from this one:

public interface ListAuthenticationActionModeViewCallbacks extends ActionModeViewCallbacks {

    void onDeleteActionClicked();


This new interface has another method, onDeleteActionClicked(), which is where the presenter gets called (check MVP if you are not aware what MVP and a Presenter are) and asked to delete the items the user has selected (if you have more than a single action, you need to create more methods, each for any action you have).

This interface must be implemented by the Fragment/Activity which wants to use the Contextual Action Mode. The implementation looks like this:

    public void onListItemSelect(final int position) {

        final boolean hasCheckedItems = listAuthenticationAdapter.getSelectedCount() > 0;

        if (hasCheckedItems && actionMode == null) {
            // there are some selected items, start the actionMode
            actionMode = ((AppCompatActivity) getActivity()).startSupportActionMode(new ListAuthenticationToolbarActionModeCallback(this, this, listAuthenticationAdapter));
        } else if (!hasCheckedItems && actionMode != null) {
            // there no selected items, finish the actionMode

       if (actionMode != null) {
            //set action mode title on item selection
            actionMode.setTitle(getString(R.string.cab_selected, listAuthenticationAdapter.getSelectedCount()));

    public void onDestroyActionMode() 
        actionMode = null;

public void onDeleteActionClicked() {

where R.string.cab_selected is

<string name="cab_selected">%1$d selected</string>

In doing startSupportActionMode() we need to pass a ActionMode.Callback item that I haven’t explained yet. Let’s create another class which implements that interface.

public class ListAuthenticationToolbarActionModeCallback implements ActionMode.Callback {

    private final ActionModeViewCallbacks actionModeViewCallbacks;
    private final ListAuthenticationAdapter listAuthenticationAdapter;

    public ListAuthenticationToolbarActionModeCallback(final ActionModeViewCallbacks actionModeViewCallbacks, final ListAuthenticationAdapter listAuthenticationAdapter) {
        this.actionModeViewCallbacks = actionModeViewCallbacks;
        this.listAuthenticationAdapter = listAuthenticationAdapter;

    public boolean onCreateActionMode(final ActionMode mode, final Menu menu) {
        mode.getMenuInflater().inflate(, menu);
        return true;

    public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) {
        return true;

    public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
        switch (item.getItemId()) {
                return true;
        return false;

    public void onDestroyActionMode(final ActionMode mode) {

Please have a look on the official documentation here to understand how ActionMode.Callback works.


See the following screenshots:

  • first one shows the initial situation before Action Mode is triggered;
  • second one shows the situation after Action Mode was triggered by long press an item;
  • third one shows the final situation after the item “Auth 2” was deleted.

contextual action bar first contextual action bar selected contextual action bar after delete


Your Contextual Action Mode should work now! I suggest you to create different menu files, Fragment/ActivityToolbarActionModeCallback and Fragment/ActivityActionModeViewCallbacks to keep everything separated.

Please note: if you rotate the device, Contextual Action Mode is lost, you need to save its state and restore it. Another post will follow, hopefully soon!

Development, Java

Java concurrency: a few examples

Sometimes we write very high level code, sometimes we don’t. I want to put here a link to a simple project which shows how to deal with concurrency in Java with a few examples.

The project is available on Github here

Goal of the project is to retrieve the details and the balance of a player and show them at the same time: until you have collected both of them you have to wait before showing the user the information.

There are two different packages: in the first, Futures and Callables are being used, in the other, Threads/Runnables and a CountDownLatch are.

Futures and Callables are the best option when you need to run a task which has a return value. I also made it in a different way using Threads/Runnables, a CountDownLatch and some listeners but these classes are usually used when you have tasks which won’t return any value.

Use the two Main classes to run the examples. Have fun!

aws, sysadmin

AWS S3 custom policy

Do you want to restrict access on S3 only to some users? Do you want to restrict the bucket they can access? Do you want to restrict the actions they can do? Let’s create an AWS S3 custom policy!

Login to your AWS console, go to the IAM console, choose Policies from the left side menu, then click on Create Policy.

Here you can create a new policy in 3 different ways, but what we will do today is following the first one, so click on Copy an AWS Managed Policy. In the next screen select AmazonS3FullAccess. Now, choose a policy name and description. Then, let’s write the policy document.

What I wanted to achieve was these:
– user A which could access only the development bucket;
– user B which could access only the production bucket.

So I created 2 policies, one for each user, that look like the following:

    "Version": "2012-10-17",
    "Statement": [
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucketname*"

Look at the * at the end of the bucket’s name. It is mandatory otherwise you won’t have permission the execute the listing operation and many other operations would fail due to this.

Another way was to create the policy this way:

    "Version": "2012-10-17",
    "Statement": [
            "Effect": "Allow",
            "Action": "s3:ListBucket",
            "Resource": "arn:aws:s3:::bucketname"
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucketname/*"

I write it only for completeness but I find the first way more compact to write and to read.

Please note you can add more attributes to the Statement object to restrict even further the permissions.

Now, after you have successfully created a policy, assuming you have already created a IAM user from the IAM console, go to that user’s info and attach the policy to it using the Permissions tab.

Do you want to test your new user and policy work as expected? Let’s assume you have created these settings:

  • User A can access only the development bucket;
  • User B can access only the production bucket.

This is what should happen:

  • User A tries to access the development bucket: permission granted;
  • User A tries to access the production bucket: permission denied;
  • User B tries to access the development bucket: permission denied;
  • User B tries to access the production bucket: permission granted.

Please refer to the AWS docs for a complete list of attributes and actions to fully customize your policy.

Android, Development

Android NoteApp with Dagger and Retrofit

Today I show a simple Android project I wrote which shows the use of Dagger, Retrofit and some other stuff.

The full source code of the project is available for you here

The project’s main purposes are the following:

  • Show Dagger2 dependency injection;
  • Show MVP architecture (made through Dagger2)
  • Show the repository pattern used to cache server data
  • Show the creation and use of a CustomView

Furthermore, I have used ButterKnife to remove the boilerplate code needed to bind classes/views, and GreenDao to automatically create the SQLite repository/model classes.

This project is based on the Google Android Architecture samples which are available here


ApplicationContextException using SpringBoot with Gradle and IntelliJ IDEA

In my spare time I decided to have a better look to SpringBoot and in doing so I decided to leave back Maven and Eclipse and to move to Gradle and IntelliJ, which I already use to develop Android applications.

During the first phase of my development I encountered a strange issue: it seems that IntelliJ IDEA will add wrong dependencies to your SpringBoot project which will cause it to crash at runtime.

This was the exception thrown and the full stack trace:

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh( ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh( ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.refresh( [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.createAndRefreshContext( [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at com.sampleapp.SampleAppApplication.main( [main/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_72]
	at sun.reflect.NativeMethodAccessorImpl.invoke( ~[na:1.8.0_72]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke( ~[na:1.8.0_72]
	at java.lang.reflect.Method.invoke( ~[na:1.8.0_72]
	at com.intellij.rt.execution.application.AppMain.main( [idea_rt.jar:na]
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory( ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer( ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh( ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	... 13 common frames omitted

This stacktrace is related to SpringBoot v1.3.3 but I experienced the same issue even with SpringBoot v1.4.0.

In the end I found that IntelliJ was putting this line in the build.gradle file:


After removing that line, the project ran without issues.
So if you are experiencing an ApplicationContextException and you couldn’t find its cause, try to have a look at your build.gradle file.


Windows 10 Wake On Lan


I was using the Wake On Lan feature of my motherboard brilliantly, but after having updated my system from Windows 7 to Windows 10 it stopped working and I had to figure out why.

Here below are the steps you need to check if you want to enable the Wake On Lan on your computer.

Enable Wake On LAN in your motherboard settings

First, you need to enter your BIOS/UEFI and check for Wake On Lan setting. It should be very simple, you should just find an option: the only thing you have to do is set it to Enabled.


Enable Wake On LAN in Windows 10 network device settings

Search for “Device Manager” from the Start Menu/toolbar and open it. Look for “Network Adapters”, if you open it you will find the list of all the network adapters you have installed in your computer (ethernet, wifi, virtual ones, etc..)

Find the one you use to connect to your LAN, and right click on it, then choose “Properties”.

The following depends on your hardware/driver version: the point as always here is to find the Wake On Lan setting. You could find it under the “Advanced” or “Power Management” tabs. Also here you need to enable the Wake On Lan property, if any, and some other properties like “Wake on Magic Packet”.


Disable Windows 10 fast startup

This step is only necessary if after have done the two previous ones the Wake On Lan isn’t yet working. Disabling this option could slightly increase your system startup but it was the only way to let my Wake On Lan work. By the way, I didn’t notice any difference between before and after startup times.

Search for “Device Manager” from the Start Menu/toolbar and open it. Now click on “Choose what the power buttons do” from the left menu. Disable “Turn on fast startup”.


If everything is setup correctly you should be able to turn on your computer from all the other computer and devices (smartphones, tablets, etc) which are connected to your LAN. There are a lot of softwares for whatever Operating System you need to perform this operation. You can also install Team Viewer on the computer you want to wake and at least on one other computer in the LAN to use this one to turn on the target machine from the Team Viewer web interface very easily with just a click!

Any suggestions/questions, feel free to write a comment below!


Install Oracle Java JDK on Linux


In this post we will find out how to install the official Oracle Java JDK on Linux.

First, you need to download the correct package for your operating system.
Go here and download the Linux .tar.gz file for x86 or x64 platform.

At the time of writing this article, the current available version is Java SE Development Kit 8u74.

Now, copy the file you just downloaded to the folder /usr/local/java by doing

sudo cp -r FILE_NAME /usr/local/java/

Now unpack the archive using this command

sudo tar xvzf FILE_NAME

Wait for the extraction to be completed, then remove the .tar.gz archive.

Now, to let the JDK folder be system-wide available, we need to add it to the PATH. To do this, let’s run this command

sudo gedit /etc/profile

and at the end of the file past these lines

export JAVA_HOME
export PATH

where DIR_NAME is the name of the directory which was created when you extracted the .tar.gz archive.

Now let’s reload our changes by running

source /etc/profile

and it’s done!

If everything went out correctly you should be able to run

java -version

and see your current installed Java version!

Happy development!


Custom Fragment Backstack in Android

Dealing with Fragments is always a pain: after some time I found a way to deal with them in a less painful way, creating a custom Fragment Backstack.

How to create your custom Fragment Backstack navigation

Put this code in your main Activity:

public class MainActivity extends AppCompatActivity {

    private Stack<Fragment> fragmentStack;

    protected void onCreate(Bundle savedInstanceState) {
        fragmentStack = new Stack<>();

    public void onBackPressed() {
        if (fragmentStack.size() == 0) {
        } else {
            showFragment(fragmentStack.lastElement(), false);

    public void showFragment(Fragment fragment, boolean addToStack) {
        if (addToStack) {
        getFragmentManager().beginTransaction().replace(, fragment).commit();


We have a fragmentStack field which is a Stack of Fragment: we use this to save the Fragments we show in our app and we initialize it in the onCreate() method of the main Activity.

In the onBackPressed() method we remove the current Fragment from the Stack and then if there is another one, we show it, otherwise we close the app because there is nothing more to be shown.

The method showFragment() is the one we use to show a Fragment on the screen; we invoke it every time we need to change the visible Fragment. If we want to save the current transaction being able to come back to the current Fragment we pass true as addToStack value, otherwise we pass false.

Have a look at the full source code on my GitHub here.