Wednesday, May 28, 2014

Add new user in Linux/Ubuntu

To add a new user using command line on an Ubuntu machine there are at least two commands that may be used: useradd and adduser

Use adduser instead of useradd if you are not totally certain useradd is the tool you want to use because:
1. useradd is a low level tool.
2. useradd will not add home directory for new user.
3. useradd will not add many other defaults for new user.
4. adduser is more user friendly (but uses useradd in backend).
5. adduser will create home directory.
6. manpages of useradd recommends use of adduser.

Use it like this:
sudo adduser <username>

and to add a system user which has no shell (cannot log in, but just run programs):
sudo adduser --system <username>
 instead of
sudo useradd <username> -s /bin/false
Using adduser, the system user a home directory will be created.

See and for good reasons with links to manpages.

Java Listeners and Adapters, almost anonymous functions

Java allows developers to easily add listeners to different events.
e.g. button.addMouseListener(this);
However, often you don't want to implement a listener interface for your class or add an inner class
MyClass implements MouseListener
MyClass {
    private class ListenerClass implements MouseListener {
            public void mouseClicked(MouseEvent e) {}
            public void mouseEntered(MouseEvent e) {}

With all the functions required by the interface cluttering up your code. Often you don't even need more than one or two of the functions.

Enter Adapters.
Adapters are classes which are made to match a listeners interface and only that. They do nothing when called, but the developer will override the function he needs:
button.addMouseListener( new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {

This adds flexibility to Java, almost like the anonymous functions of JavaScript.


Wednesday, May 7, 2014

Play2 PersistenceException

You might come across the error:
[PersistenceException: Error loading on models.Period.startYear]
in Play 2 Framework.
This is most likely caused by your database having a NULLable field which doesn't map to a nullable member in the model.

You database has the following fields:

 which means start_year may be (null) or an int.

Your java model has the following members:
public class Period extends Model {
    public Long periodId;

    public int startYear;
    public int endYear;

Which means that startYear may be an int, but not null.

To fix, make change the database fields to not be nullable.
Or the java model members nullable also, by using the Integer object wrapper instead of int:
public class Period extends Model {
    public Long periodId;

    public Integer startYear;
    public Integer endYear;