Java application as Linux Service in 4 steps

If you are reading this post then, probably, you need to execute your java app as a Linux service.

This can be done in 4 really easy steps

  • Create the service
  • create a bash script
  • give execution permission to the bash file
  • enable and start your brand new service

Step 1: create the system service

sudo nano /etc/systemd/system/MyFantasticJavaApp.service

it will open the nano editor. Add the following, changing the working directory and the User values based on your convenience

                                                                                                 
 [Unit]
 Description=good old Java application
 [Service]
 User=root  
 # The configuration file application.properties should be here:
 # change this with your workspace
 WorkingDirectory=/usr/local/javaproject/

 #path to executable.
 #executable is a bash script which calls jar file
 ExecStart=/usr/local/javaproject/myBashFile
 SuccessExitStatus=143
 TimeoutStopSec=10
 Restart=on-failure
 RestartSec=5
 [Install]
 WantedBy=multi-user.target

save the file (Ctrl-X, select Y(es) and press enter)

Step 2: create the bash script

Now let’s create a script which will basically call our jar/war file.

This file has to be the one specified in previous service file (what we call in ExecStart value). So, let’s write:

sudo nano /usr/local/javaproject/myBashFile

it will open (again) the nano editor. Add the following 2(two) lines, changing the port and the path to your jar/war file

#!/bin/sh
 sudo /usr/bin/java -Dserver.port=7080  -jar /usr/local/javaproject/MyFantasticJavaApp.jar

save the file (Ctrl-X, select Y(es) and press enter)

Step 3: give execution permission to the basch script

this is the simpler step. Just write this, changing the file and his path:

sudo chmod u+x /usr/local/javaproject/myBashFile

Step 4, almost there: let’s play the new service

sudo systemctl daemon-reload
sudo systemctl enable MyFantasticJavaApp.service
sudo systemctl start MyFantasticJavaApp

Et voila! Do not thank me!

Two raspberry command line every newbie has to know

1) pinout

This tool is provided by the GPIO Zero Python library, 

It allows you to know better the GPIO map of your raspberry. So GPIO number, which are for 5v/3.3v and which are for negatives

Installation

Before we can use the pinout tool, we need to first update the package list by running the following command.

sudo apt update

Then, we can install the package that will provide us with the pinout tool by using the command below.

sudo apt install python3-gpiozero

and finally

pinout

2) gpio readall

Basically the library name is WiringPi, and you can use it to manage many of the functionalities provided by the GPIO header: digital pins, SPI, I2C, UART, etc.

to installi it:

sudo apt-get install wiringpi

to check if the installation went ok:

gpio -v

Ok, now it’s the moment to show it in action:

gpio readall

you should get something like this:

it shows every pin of your raspberry boards and

  1. the numbering of the pin
  2. the voltage (in case of voltage pin)
  3. if it’s in use (1) or not (0)
  4. set High or Low voltage for each pin through command line (for example gpio -g write 33 1 give voltage to pin number 33 gpio -g write 33 0, remove voltage to that pin number 33)

Save username and password in git

Lately I started to work on a new environment and the first thing has been to install git.

The second thing has been to clone a repository and finally I started to pull and push things.

But! Every time I pulled and pushed something a very nasty little window started bothering me: insert username, insert password (because of course the repository was protected by a password)

And if initially I endured it, after the third time I started to hate it.

So…I decided to save locally my git username and password.

First I had to type this

git config --global credential.helper store

and then

git pull (or push)

You will be prompt (for the LAST TIME) the git username and password

They will be stored in a .git-credentials file in a clear format like:

https://username:password@repository

Normally this file is saved in your local [username] folder (in windows or linux OS)

There is the possibility to have a secure (and recommended) method using a ssh key. Alternatively you can use a caching timeout way of saving your credentials (just in memory for a limited period of time).

For a complete documentation please refer to:

https://git-scm.com/docs/git-credential-store

https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage

Major.Minor.Patch


Every time you release a public (API) software you must update his version number.

The (public) version is universally composed by 3 numbers separated by a point:

Each version number has a semantic representation

The pattern is 

Major.Minor.Patch

Ex: in version number 10.2.5

10 is the Major version

2 is the Minor version

5 is the Patch version

All of these 3 numbers are always 

Incremented

NEVER decremented

Positive starting by 0

Patch number

It is incremented each time the release is about fixing some bug without affecting the already existing public interface

So if you see a version number like: 1.1.5 it means the last 5 releases were about fix bugs.

Minor number

As opposed to Patch, Minor means that they have been released new (interesting) public feature, without impacting old ones.

When there is a new Minor release the Patch number is restarted to 0. Of course, together to new feature, it’s possible that also some bug fixes have been released (even though the Patch number is 0)

Major Number

When the Major number is incremented the release contains new (fantastic) features, buuuut it means that all the old features are not anymore compatible! So if you depend on those, pay attention.

If you think about it, these versioning rules could be applied also to humans.

Each 1st of January we always have new proposals for our self, so it’s like we “would” change our Major version. Or whenever we learn something new we could upgrade our Minor version.

But when do we change our Patch Number? Maybe each time we have makeup?

toString() to JSON with Eclipse

right click –> Source –> generate toString() –> Generated code fieldset –> Edit button –> New.. button –> give a name (ex. JSON) –> copy and paste this pattern:

{"${member.name()}":"${member.value}", "${otherMembers}"}

That’s it.

Hope this help!

How to implement unstable behavior / requirement

The customer, as we know, is always right even when he returns on his steps, and he forces you to review / rewrite a behavior for a component that seemed clear.

But the worst has not yet arrived, because the user can ask to change that requirement again, or worse, put things back as they were before.

Fortunately, Object Orientation comes to your aid with one of the most important design principles.

“Identify aspects of application that vary and separate them from what stays the same.”

If you have a feature of your program that

  • your client asks you to change several times
  • or simply that it can have different behaviors based on different inputs

then it is necessary to extract it from the main context and create one or more components that implement these different versions / behaviors.
Don’t be fooled to use the inheritance! In this case, in fact, inheritance cannot help you because there is the risk of having unwanted behavior performed.

Even the interfaces may not be sufficient because it forces you to write methods that are not used or to write the same method several times, duplicating the code.

Solution
Create a set of classes for each feature that tends to vary, where each class represents a possible behavior
Of course this set of classes implements the same interface.

Furthermore, following the principle
“Program with Interface and not with implementation”

to implement “unstable requirement” you will refer this interface in the main system.

In this way your client can change his mind whenever he wants, and you will be ready to please him and, perhaps, become his best friend or psychologist …

How to integrate young framework like React in old web pages

In these days I’m trying to improve the user experience of an old JSP page. So I thought of injecting into it some custom components of the framework react.

Integrate a basic React app inside an existing web page, like for example an HTML or JSP or PHP page, is very very simple and, most important thing, it does not require a build and an import of tons of prebuild files.

Below an example of how to do this integration inside a generic html page.

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/babel" src="/js/app.js"></script>

<div id="react-content" />

<script type="text/babel">
ReactDOM.render(<CustomApp />, document.getElementById('react-content'));
</script>

And nothing special in app.js file than a classic CustomApp class react component!

The possibility of using React directly in existing web pages, without big frills and various builds, is really very convenient.
I don’t know if Angular can also be used in the same way. I’ll try in the next few days.


Architecture stack for 2019

When an IT consultant/architect/developer wakes up in the morning he knows that he has to study a new programming language before the fullstack runs away.

And that the new programming language tomorrow is already deprecated.

If you want to save your big fat neck today you have to know at least 80% of next languages.

Frontend layer

Angular and or React (better both, I know it’s not possible if you have also a private life).

If you have to choose today, for example, if you start programming now, I bet on React.
Rest WS as a client

Backend layer

Node.js and or Java (Spring it’s enough).
API Rest WS (Ok with Spring).

DB layer

MongoDb (or any nosql db) and or Oracle (or MySql or any sql db)

But there is good news. All Network layer is simple to manage now, thanks to different infrastructure-as-service like AWS, Firebase and Heroku

If you know all above things, well, you can continue sleep 30 minutes more!

Amazon is eating also System and server administrators

With so much of computing becoming cloud-based (see AWS or Google Cloud), the general IT person who patrolled your office is becoming less and less relevant in today’s workforce.

The change is already happening at smaller businesses, which find it cheaper and more efficient to outsource the work. Yes, like me for example.

The good news is that it is creating the opportunity for programmers, freelancers and system administrators willing to pivot to manage their client servers remotely and profitably, and at better scale.

So, maybe, system administrator could see this thing from another perspective. What do you think?

Exceptions in the life: Checked vs Unchecked problems

In Java, as well as in your life, there two type of exception:

  1. checked exception that are the expected problems
  2. unchecked exception, that are the unexpected problems.

As in the life, for the expected events you are prepared because you plain to have that problem. So you are organized to intercept and block that problem. For example, if you are a student, or you have been a student, you know that your teacher could exam you. To avoid a negative
vote, or problem with you parents , you (theoretically) study. If you don’t study enough you could have a bad vote. But basically you are aware.

In Java is exactly the same, apart from the fact that problems are named Exception. You, and also the compiler, know that you can expect an exception calling a method and then you prevent that exception intercepting it with a try-catch-finally block.

int vote;
try{
vote=teacher.exams(you);
}
catch(NoStudiedException nse){
vote=VOTE.Very_Bad;
}
finally{
register.setVote(you,vote);
}

In Java you are aware because exists the throws clause that forces you to face up to your problem.

The exams method of Teacher class is like below:

public int exams(Student student) throws NoStudiedException{

}

But, unfortunately, there are no just checked exception. We can have also unexpected exception that you and the compiler are not aware, for example RuntimeException, ArrayIndexOutOfBoundException, but above all: NullPointerException.

They are all problems you could never have imagined it could happen to you. They are Unchecked.

All exception under Error and RuntimeException classes are Unchecked

You have to know the difference even because there are some framework that have different behavior based on checked and unchecked events.

For example JPA, that is in charge of transactions, makes an automatic rollback just in case of unchecked exception, BUT doesn’t make the same for the checked ones. It means that, if you use JPA and you want rollback when a CheckedException happens, then you have manually rollback out, adding the clause “rollbackFor=<CheckedException>.class” above the method. If you don’t use JPA and his children/nephew then pretend I did not say anything…