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

Development

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(EmbeddedWebApplicationContext.java:133) ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at com.sampleapp.SampleAppApplication.main(SampleAppApplication.java:16) [main/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_72]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_72]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_72]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_72]
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) [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(EmbeddedWebApplicationContext.java:185) ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:158) ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130) ~[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:

providedRuntime(‘org.springframework.boot:spring-boot-starter-tomcat’)

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

Windows 10 Wake On Lan

network-cables

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.

Done!

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”.

Done!

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”.

Done!

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!

GNU/Linux

Install Oracle Java JDK on Linux

java

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

JAVA_HOME=/usr/local/java/DIR_NAME
PATH=$PATH:$JAVA_HOME/bin
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!

Android

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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentStack = new Stack<>();
    }

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

    public void showFragment(Fragment fragment, boolean addToStack) {
        if (addToStack) {
            fragmentStack.push(fragment);
        }
        getFragmentManager().beginTransaction().replace(R.id.container_fragment, 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.

Android

Auto hide keyboard using Android EditText

Do you want to automatically hide your keyboard whenever you touch outside it? Please continue reading and you will find out how to do it!

First, we will create our AutoHideKeyboardEditText class like the following:

public class AutoHideKeyboardEditText extends EditText {

    public AutoHideKeyboardEditText(Context context) {
        super(context);
        init();
    }

    public AutoHideKeyboardEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AutoHideKeyboardEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(v);
                }
            }
        });
    }

    private void hideKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager)
            view.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

Whatever Constructor is used, we set an onFocusChangeListener to hide the keyboard using the proper method if we touch outside the EditText area (if the focus is not anymore on it).

Afterwards, create a layout similar to this

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical">

being sure, whatever layout you want to use, to add clickable and focusableInTouchMode attributes with true value.

Now just add our AutoHideKeyboardTextView inside that layout. You can simply add it using XML like the following

<com.w3ma.androidshowcase.autohidekeyboard.AutoHideKeyboardEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

 

You are done! Whenever you touch outside the EditText the keyboard will be automatically dismissed!

Please note: you should add theĀ clickable andĀ focusableInTouchMode attributes to the outermost view but if it is a ScrollView this might not work. For such case, those attributes could be added to the view directly under the ScrollView.

Full source code on my GitHub repository here.

Source:https://stackoverflow.com/questions/4165414/how-to-hide-soft-keyboard-on-android-after-clicking-outside-edittext/19828165#19828165

I don’t know why this wasn’t voted as the best answer because it is indeed.

Android

Android Studio gitignore to avoid useless files

Create a perfect Android Studio .gitignore file is sometimes tedious, so I have gathered some information on the Internet, mainly on StackOverflow, I made some experiments with my sample project over and over and finally I obtained a perfect Android Studio .gitignore file.

Usually, I create my project inside a parent folder which I initialize as my Git repository.

So, for example, this is a sample structure (folders are bolded):

AndroidShowcaseRepository

  • .git
  • AndroidShowCase
    • .gradle
    • .idea
    • app
    • build
    • gradle
    • .gitignore
    • AndroidShowcase.iml
    • build.gradle
    • gradlew
    • gradlew.bat
    • local.properties
    • settings.gradle
  • .gitignore
  • LICENSE
  • README.md

I use the following as content for the .gitignore file in the AndroidShowcaseRepository folder

# Built application files
*.apk
*.ap_

# Files for the Dalvik VM
*.dex

# Java class files
*.class

# Generated files
bin/
gen/

# Gradle files
.gradle/
build/
/*/build/

# Local configuration file (sdk path, etc)
local.properties

# Proguard folder generated by Eclipse
proguard/

# Log Files
*.log

and the following as content for the .gitignore file in the AndroidShowcase folder

.gradle
/local.properties
.DS_Store
/build
/captures
.idea
gradlew
gradlew.bat
gradle

Using these two .gitignore files (and the default ones created by Android Studio inside the app folder and into other folders you could have) you will likely save only the necessary source code to your repository and not files which could be generated by Android Studio itself.

Check w3ma showcase repository for the complete source code and for more explanation!

Android

Making TextView with clickable link in Android

I will explain how to create a TextView with inside a clickable link in Android.

Do you want to open a static link without doing other operations? So just follow the first part of this tutorial! Otherwise, if you want to have more control on the link customization and operations after the user taps on it, follow the second part of the tutorial.

STATIC CLICKABLE LINK INSIDE STRINGS.XML RESOURCE

Let’s create an example TextView in your layout like this one:

<TextView
    android:id="@+id/messageWithLinkTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:text="@string/messageWithLink" />

Create this string in strings.xml:

<string name="messageWithLink">This is a message with a link inside!\n<a href="https://www.google.com/">Tap here to open it!</a></string>

Write this code in your activity/fragment:

@Bind(R.id.messageWithLinkTextView)
TextView messageWithLinkTextView;

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ButterKnife.bind(this, view);
    messageWithLinkTextView.setMovementMethod(LinkMovementMethod.getInstance());
}

Please note: I’m using ButterKnife library to bind fields and views (I suggest you to have a look at this fantastic library!)

You are done! You should get a TextView like the one in the following screenshot and when you tap on the hyperlink the browser should open! Cool!

textview_with_clickable_link

P.S. unfortunately I didn’t find a way of achieving this only using XML properties. If anyone knows how to do it, please let me know in the comments!

CUSTOM CLICKABLE LINK AND CUSTOM ACTIONS

Create another TextView in your layout:

<TextView
   android:id="@+id/messageWithSpannableLinkTextView"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:gravity="center"
   tools:text="@string/messageWithSpannableLink" />

Create another string resource in strings.xml:

<string name="messageWithSpannableLink">This is a message with a spannable link inside!\nTap here to open it!</string>

Please note: this time there is no <a href/> tag inside the string!

Now write this code in your activity/fragment:

@Bind(R.id.messageWithSpannableLinkTextView)
TextView messageWithSpannableLinkTextView;

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ButterKnife.bind(this, view);
    SpannableString spannableString = new SpannableString(getString(R.string.messageWithSpannableLink));
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View textView) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com")));
        }
    };
    spannableString.setSpan(clickableSpan, spannableString.length() - 20,
            spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    messageWithSpannableLinkTextView.setText(spannableString, TextView.BufferType.SPANNABLE);
    messageWithSpannableLinkTextView.setMovementMethod(LinkMovementMethod.getInstance());
}

You are done! You should get a TextView like the one in the following screenshot and when you tap on the hyperlink the ClickableSpan->onClick() method should be called, so you can do your operations and let the browser open the link! Cool!

textview_with_spannable_clickable_link

Check out the complete source code on my GitHub here!