How do I clear the current command line in terminal?

Terminal

You have type a long line of command in terminal. But now you want to clear or delete the entire line. Deleting each character in the command will take sometime and bored you. So are there any keyboard shortcuts that allow you to do this? Yes there are some hotkeys to the rescue.

Hotkeys Description
CTRL + u Delete the current command.
The deleted command will be stored into a buffer.
CTRL + w Delete a word.
CTRL + c Abort what you are typing.
CTRL + d Delete current character.

Other hotkeys that might help you work faster in the terminal.

Hotkeys Description
CTRL + e Move to the end of line.
CTRL + a Move to the start of line.
CTRL + k Cut text from the cursor to the end of line.
CTRL + y Paste the last cut text or buffer.
CTRL + - Undo.
CTRL + b Backward one character.
CTRL + f Forward one character.
ALT + Backward one word.
ALT + Forward one word.

How do I generate random alphanumeric strings?

The following code snippet demonstrates how to use RandomStringGenerator class from the Apache Commons Text library to generate random strings. To create an instance of the generator we can use the RandomStringGenerator.Builder() class build() method. The builder class also helps us to configure the properties of the generator. Before calling the build() method we can set the properties of the builder using the following methods:

  • withinRange() to specifies the minimum and maximum code points allowed in the generated string.
  • filteredBy() to limits the characters in the generated string to those that match at least one of the predicates supplied. Some enum for the predicates: CharacterPredicates.DIGITS, CharacterPredicates.LETTERS.
  • selectFrom() to limits the characters in the generated string to those who match at supplied list of Character.
  • usingRandom() to overrides the default source of randomness.

After configuring and building the generator based the properties defined, we can generate the random strings using the generate() methods of the RandomStringGenerator. There are two methods available:

  • generate​(int length) generates a random string, containing the specified number of code points.
  • generate​(int minLengthInclusive, int maxLengthInclusive) generates a random string, containing between the minimum (inclusive) and the maximum (inclusive) number of code points.

And here is your code snippet:

package org.kodejava.example.commons.text;

import org.apache.commons.text.CharacterPredicates;
import org.apache.commons.text.RandomStringGenerator;

public class RandomStringDemo {
    public static void main(String[] args) {
        RandomStringGenerator generator = new RandomStringGenerator.Builder()
            .withinRange('0', 'z')
            .filteredBy(CharacterPredicates.DIGITS, CharacterPredicates.LETTERS)
            .build();

        for (int i = 0; i < 10; i++) {
            System.out.println(generator.generate(10, 20));
        }
    }
}

Below are examples of generated random alphanumeric strings:

iDp323cGhbnvHBq
fuOHpaM0x8B9eFBR2tr
T8JmM8jeRN
SSP1ZsFsIyP
GPr7rDbwr33zO
s7HkOlcT6gLQoWOfV6
WMgmVfhxp0
OTj9UUBdnT51TgACK
VmRzheeRyVZJKGo7
xzyD31Vk7Fx

Maven Dependencies

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-text/1.6/commons-text-1.6.jar -->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-text</artifactId>
  <version>1.6</version>
</dependency>

Maven Central

Apache Logo

Why do I get ArrayIndexOutOfBoundsException in Java?

The ArrayIndexOutOfBoundsException exception is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Array with 10 elements

For example see the code snippet below:

String[] vowels = new String[]{"a", "i", "u", "e", "o"}
String vowel = vowels[10]; // throws the ArrayIndexOutOfBoundsException

Above we create a vowels array with five elements. This will make the array have indexes between 0..4. On the next line we tried to access the tenth element of the array which is illegal. This statement will cause the ArrayIndexOutOfBoundsException thrown.

We must understand that arrays in Java are zero indexed. The first element of the array will be at index 0 and the last element will be at index array-size - 1. So be careful with your array indexes when accessing array elements. For example if you have an array with 5 elements this mean that the index of the array is from 0 to 4.

If you are trying to iterate an array using for loop. Make sure the index start from 0 and execute the loop while the index is less than the length of the array, you can get the length of the array using the array length property. Let’s see the code snippet below:

for (int i = 0; i < vowels.length; i++) {
    String vowel = vowels[i];
    System.out.println("vowel = " + vowel);
}

Or if you don’t need the index you can simplify your code using the for-each or enhanced for-loop statement instead of the classic for loop statement as shown below:

for (String vowel : vowels) {
    System.out.println("vowel = " + vowel);
}

How to create a read-only MySQL user?

MySQL Logo

Introduction

There are times when you need to create a user only to have a read-only access to a database. The user can view or read the data in the database but they cannot make any changes to the data or the database structure.

Creating a New User Account

To create a read-only database user account for MySQL do the following steps:

  • First, login as a MySQL administrator from your terminal / command prompt using the following command:
mysql -u root -p
  • You’ll prompted to enter the password. Type the password for the root account.
  • Create a new MySQL user account.
CREATE USER 'report'@'%' IDENTIFIED BY 'secret';

The % in the command above means that user report can be used to connect from any host. You can limit the access by defining the host from where the user can connect. Omitting this information will only allow the user to connect from the same machine.

  • Grant the SELECT privilege to user.
GRANT SELECT ON kodejava.* TO 'report'@'%';
  • Execute the following command to make the privilege changes saved and take effect.
FLUSH PRIVILEGES;
  • Type quit to exit from the MySQL shell.

Test the New User Account

  • Now we can try the newly created user account. Start by login with the new user account and provide the corresponding password.
mysql -u report -p
  • Try executing the DELETE command:
mysql> USE kodejava;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> DELETE FROM authors;
ERROR 1142 (42000): DELETE command denied to user 'report'@'localhost' for table 'authors'
mysql> UPDATE authors SET name = 'Wayan Saryada' WHERE id = 1;
ERROR 1142 (42000): UPDATE command denied to user 'report'@'localhost' for table 'authors'
mysql>

How do I define access modifiers in Lombok’s @Getter and @Setter annotations?

By default when we use the Lombok’s @Getter and @Setter annotations the getters and setters will be created with public access modifier. We can however change the access modifier by setting the AccessLevel of the @Getter and @Setter annotations. The available choices for the access level are AccessLevel.PUBLIC, AccessLevel.PROTECTED, AccessLevel.PACKAGE, AccessLevel.PRIVATE. These enum values correspond to Java’s access modifier. While the AccessLevel.NONE will disable the getter and setter method generation.

package org.kodejava.example.lombok.domain;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

@Getter @Setter
public class Person {
    @Setter(AccessLevel.PROTECTED)
    private String firstName;

    private String lastName;
    private String gender;

    @Getter(AccessLevel.PRIVATE)
    private int age;
}

How we use the Person class show in the snippet below:

package org.kodejava.example.lombok;

import org.kodejava.example.lombok.domain.Person;

public class PersonDemo {
    public static void main(String[] args) {
        Person person = new Person();
        person.setLastName("Bar");
        person.setGender("M");
        person.setAge(20);

        System.out.println(person.getFirstName());
        System.out.println(person.getLastName());
        System.out.println(person.getGender());
    }
}

If we try to see the generated class of the Person class we can run the following command to disassemble the class.

javap -p -cp . org.kodejava.example.lombok.domain.Person

And we got the following output of the javap command. As we can see that the setFirstName() method have a protected access modifier and the getAge() method have a private access modifier. The other mutator and accessor method all set to public access modifier.

public class org.kodejava.example.lombok.domain.Person {
  private java.lang.String firstName;
  private java.lang.String lastName;
  private java.lang.String gender;
  private int age;
  public org.kodejava.example.lombok.domain.Person();
  public java.lang.String getFirstName();
  public java.lang.String getLastName();
  public java.lang.String getGender();
  public void setLastName(java.lang.String);
  public void setGender(java.lang.String);
  public void setAge(int);
  protected void setFirstName(java.lang.String);
  private int getAge();
}

Maven Dependencies

<!--https://search.maven.org/remotecontent?filepath=org/projectlombok/lombok/1.18.4/lombok-1.18.4.jar-->
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.4</version>
</dependency>

Maven Central

How do I generate getters and setters with Lombok?

The following code snippet show you how to use Project Lombok‘s @Getter and @Setter annotations to generate getters and setters method in your POJO (plain old java objects) classes. Using these annotations remove the need to manually implements the mutator and accessor methods. Although most IDE allows you the generate these methods, using Lombok makes your classes look cleaner, especially when you have a long list of fields.

Here is a simple User class with a handful fields. We will use the @Getter and @Setter annotations on the class level. This will generate the getters and setters method for any non-static fields in the class.

package org.kodejava.example.lombok.domain;

import lombok.Getter;
import lombok.Setter;

import java.time.LocalDate;

@Getter
@Setter
public class User {
    private Long id;
    private String username;
    private String password;
    private LocalDate lastLogin;
    private boolean active;
}

Each fields in the class will have its corresponding getter and setter. For example the username field will have the getUsername() and setUsername() method. If the field type is boolean such as active it will generate the method setActive() and isActive() method.

Because the accessor and mutator already handled by Lombok, we can use the User class as if we manually implements the getters and setters method.

package org.kodejava.example.lombok;

import org.kodejava.example.lombok.domain.User;

import java.time.LocalDate;

public class UserDemo {
    public static void main(String[] args) {
        User user = new User();
        user.setId(1L);
        user.setUsername("foo");
        user.setPassword("secret");
        user.setLastLogin(LocalDate.now());
        user.setActive(true);

        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getLastLogin());
        System.out.println(user.isActive());
    }
}

If for some reasons you want to disable the getter and setter on specific field, or you want the change the access level, you can use the AccessLevel enums value for the @Getter and @Setter annotations. For example in the code snippet below the username will have no getter and setter while the lastLogin getter and setter will have protected access modifier. The AccessLevel enums includes PUBLIC, MODULE, PROTECTED, PACKAGE, PRIVATE and NONE.

package org.kodejava.example.lombok.domain;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDate;

@Getter
@Setter
public class User {
    private Long id;
    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private String username;
    private String password;
    @Getter(AccessLevel.PROTECTED)
    @Setter(AccessLevel.PROTECTED)
    private LocalDate lastLogin;
    private boolean active;
}

Maven Dependencies

<!--https://search.maven.org/remotecontent?filepath=org/projectlombok/lombok/1.18.4/lombok-1.18.4.jar-->
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.4</version>
</dependency>

Maven Central

How do I write JSON string using JSON-Java (org.json) library?

The following code snippet show you how to create JSON string using JSON-Java library. Create an instance of JSONObject and use the put() method to create a key-value pair for the JSON string. The JSONArray object can be used to create an array of list of values to the JSON string, we also use the put() method to add value to the list.

The JSONObject.toString() method accept parameter called indentFactor, this set the indentation level of the generated string, which also make the JSON string generated easier to read and look prettier.

package org.kodejava.example.json;

import org.json.JSONArray;
import org.json.JSONObject;

public class WriteJSONString {
    public static void main(String[] args) {
        JSONObject object = new JSONObject();
        object.put("id", 1L);
        object.put("name", "Alice");
        object.put("age", 20);

        JSONArray courses = new JSONArray();
        courses.put("Engineering");
        courses.put("Finance");
        courses.put("Chemistry");

        object.put("courses", courses);

        String jsonString = object.toString(2);
        System.out.println(jsonString);
    }
}

The result of the code snippet above is:

{
  "courses": [
    "Engineering",
    "Finance",
    "Chemistry"
  ],
  "name": "Alice",
  "id": 1,
  "age": 20
}

Maven Dependencies

<!-- https://search.maven.org/remotecontent?filepath=org/json/json/20180813/json-20180813.jar -->
<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20180813</version>
  <type>bundle</type>
</dependency>

Maven Central

How do I read JSON file using JSON-Java (org.json) library?

In this example we are going to use the JSON-Java (org.json) library to read or parse JSON file. First we start by getting the InputStream of the JSON file to be read using getResourceAsStream() method. Next we construct a JSONTokener from the input stream and create an instance of JSONObject to read the JSON entries.

We can use method like getString(), getInt(), getLong(), etc to read a key-value from the JSON file. The getJSONArray() method allow us to read an list of values returned in JSONArray object. Which can be iterated to get each values represented by the key. Let’s see the detail code snippet below.

package org.kodejava.example.json;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.InputStream;

public class ReadJSONString {
    public static void main(String[] args) {
        // info.json
        // {
        //  "id": "1",
        //  "name": "Alice",
        //  "age": "20",
        //  "courses": [
        //    "Engineering",
        //    "Finance",
        //    "Chemistry"
        //  ]
        //}
        String resourceName = "/info.json";
        InputStream is = ReadJSONString.class.getResourceAsStream(resourceName);
        if (is == null) {
            throw new NullPointerException("Cannot find resource file " + resourceName);
        }

        JSONTokener tokener = new JSONTokener(is);
        JSONObject object = new JSONObject(tokener);
        System.out.println("Id  : " + object.getLong("id"));
        System.out.println("Name: " + object.getString("name"));
        System.out.println("Age : " + object.getInt("age"));

        System.out.println("Courses: ");
        JSONArray courses = object.getJSONArray("courses");
        for (int i = 0; i < courses.length(); i++) {
            System.out.println("  - " + courses.get(i));
        }
    }
}

The result of the code snippet above is:

Id  : 1
Name: Alice
Age : 20
Courses: 
  - Engineering
  - Finance
  - Chemistry

Maven Dependencies

<!-- https://repo1.maven.org/maven2/org/json/json/20180813/json-20180813.jar -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

Install IntelliJ IDEA Community Edition and Write Hello Kotlin Program

To write Kotlin program you will need an IDE (Integrated Development Environment). One of the IDE that you can use is the IntelliJ IDEA CE (Community Edition). It comes with Kotlin Java Runtime Library so you don’t need to install it separately.

To run Kotlin program you will need to install the latest JDK (Java Development Kit) which can be downloaded freely from the Java Download Website. Download version for your operating system and run the installer.

To check if Java successfully installed you can type the following command in your terminal or command prompt:

java -version

If you see something this then Java Development Kit is installed in your system.

java version "10" 2018-03-20
Java(TM) SE Runtime Environment 18.3 (build 10+46)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10+46, mixed mode)

After installing the JDK you can download the IntelliJ IDEA CE. Double click the installer to install it. For more details on installation and setup you can checkout this website.

Now let’s create our first simple Kotlin program in IntelliJ IDEA.

  • Open the IntelliJ IDEA CE and click the Create New Project from the Welcome Screen dialog.
Create New Kotlin Project

Create New Kotlin Project

  • On the New Project dialog choose Kotlin from the left sidebar and then choose Kotlin/JVM in the selection on the right sidebar. Press the Next button.
New Kotlin Project Setup

New Kotlin Project Setup

  • Enter the project name Hello Kotlin, the project location path and the JDK will be used in the project.
New Kotlin Project Configurations

New Kotlin Project Configurations

  • Click the Finish button to create the project. It will bring you to the following screen.
HelloKotlin Project in IntelliJ IDEA CE

HelloKotlin Project in IntelliJ IDEA CE

  • Right click on the src directory and choose NewKotlin File/Class from the menu. Enter HelloKotlin in the File/Class name.
New Kotlin File/Class Dialog

New Kotlin File/Class Dialog

  • In the HelloKotlin.kt type in the following code snippet.
fun main(args: Array<String>) {
    if (args.isEmpty()) {
        println("Hello, World!")
        return
    } else {
        println("Hi, hello ${args[0]}!")
    }
}
  • To run it, right click on the editor and choose the Run HelloKotlinKt from the menu.
  • If you want to run it with an argument you can set it in the Run/Debug Configurations dialog.
  • To open the Run/Debug Configurations click the down-arrow button next to HelloKotlinKt in the navigation bar on the top-right and choose Edit Configurations…
  • Type in the arguments in the Program arguments textbox.
Run/Debug Configurations

Run/Debug Configurations

That’s all. Now you have your JDK, IntelliJ IDEA CE installed and created your first Kotlin program. If you have any questions please post it in the comments section below. Thank you and have fun with Kotlin.

How do I write Hello World in Kotlin?

In Kotlin, the HelloWorld.kt program can be written as a simple function like the following snippet.

fun main(args: Array<String>) {
    println("Hello, World!")
}

From this little code snippet we can learn the following features of the Kotlin programming language:

  • Kotlin program saved in a file with .kt extension.
  • The fun keyword to declare a function to show you that programming can be fun again 😉
  • To declare variables we start with the variable name followed by its type separated by a colon.
  • We don’t have to end a statement with a semicolons.
  • To print we can use the println function, which is a wrapper to Java System.out.println.
  • The main function is the execution entry point of our HelloWorld program.
  • We can create functions at the top level file without creating a class.

To compile the HelloWorld.kt program we run the following command:

kotlinc HelloWorld.kt

The compiler creates a class file called HelloWorldKt.class. To run it type the following command, assumed that you’ve setup the $KOTLIN_LIB environment variable. In my case the variable is set to /usr/local/Cellar/kotlin/1.2.40/libexec/lib.

java -cp $KOTLIN_LIB/kotlin-stdlib.jar:. HelloWorldKt