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.

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>

Step-By-Step Guide to Creating and Inserting a Java API in Eclipse

Eclipse is the most popular Java Integrated Development Environment (IDE). Just check out the survey result.

**Image Source: **IProgrammer

Here is one more for you.

Image Source Qiita

Some people say that Eclipse is dying. However, we can see that many developers still prefer using Eclipse. Let’s get Eclipse popularity part out of the way and talk about how you can insert a Java API in Eclipse. You can do it quickly. But before getting to adding and creating API, I will educate about Java API for readers who do not have in-depth knowledge of Java API.

What is Java API?

The full form of API is Application Programming Interface (API). Java language comprises various syntax and semantics. The set of classes that are inside the Java Development Environment is known as Java API.

The classes in Java API are in Java language, and it runs via a Java Virtual Machine. You can find every single thing inside Java API, ranging from collection classes to GUI classes.

To get the most out of Java API, you need to have a firm grasp of Java programming language. Java is the most popular language in the world today, and huge corporations love Java due to its great documentation and security features.

If you want to land a project in Java, it is beneficial to undertake a Java Certification Training course that gives clear insights about various aspect of the language being a big plus for novice as well as tech professionals.

There are various levels in Java certification courses. You can slowly jump from one level to the another and learn as you go. You can write some codes on the side while going through the Java certification courses.

How to Create and Insert a Java API in Eclipse?

Now that you are aware of Java API, we can talk about the process of creating and inserting a Java API in Eclipse.

To create a great program without wasting much time, you need to work in a framework. If you are among the developers who are looking to develop your API via Eclipse, you are in the right place. I will show you a step-by-step guide to creating and inserting a Java API in Eclipse. All you need to do is systematically follow my instruction.

Project Creation

The first task is a project creation. Here are the steps:

  • Enter the current workspace inside Eclipse. It is better to create a new workspace to ensure that you do not mess your projects.
  • After the first step, you need to make a new Java Project and give whatever name you like. However, you should make sure that your name relates to your project.
  • After the project creation, you need to test if you can see your project in an explorer window or not. It is essential to make sure that it does not mess around with other projects.

Fresh Package and Class

  • Head to project explorer and right click your project. After selecting a new package, name it. It will act as the main class file.
  • Head to package, click new, and then select class under the source folder. Give a relevant name to the class. Make the class, public and do not make the main method stub in class.
  • After the completion of the first two steps, double-click your class file.

Time to Add Code and Export

  • You can now add some codes to your project. For now, create some random static methods that return something.
  • When you finish adding methods to your class, export it as a jar file. It is a simple process. Go to the project source folder and select Export. Then click on Java and select JAR file. Note down the export location, so that you will be able to access it later. You can then click on the Finish button and let the Eclipse do the rest for you.

Do the Testing

  • You are now all set to do some testing. Just create a project like in step number 1. Name it different this time around.
  • There is no need to export it because it is a test project. Instead of exporting, go with creating a package. Just create a new class and name it “test.” You can now inherit the public static void main method. Select the finish button after completing the process.
  • You will observe a class file with the primary method when you smash the finish button. In case you fail to see the class file, copy the code below.

Create a JAR for Building a Path

You are in the ending part of creating and inserting a Java API. You have a primary method ready. Now, you should add API to a build path of the new project.

  • Select your new project and then go to properties.
  • Select “Java Build Path” on the properties–>window.
  • Select Libraries after entering the “Java Build Path” in the properties menu.
  • Click on “Add External JARs..” and go to your API location and then select open.
  • Click the open button to finish the step number 5.

Time to Run your API

You are finally ready for a climax. You have now created your API. What to do next? Just implement your API and observe your computer screen. If there are errors, go through the article once again to see if you missed something along the way.

Over To You

Did you find it challenging to create and insert Java API to Eclipse? Hopefully not. It is so easy that you can finish the task of creating and adding Java API to Eclipse within 10-30 minutes. After the installation of Java API, you can complete your projects in a shorter period.

Remember, smart programmers not only work hard, but they work smart as well. Creating and inserting Java API to Eclipse is the first step to working smart. I hope you have found value in this article. If you have any confusions, feel free to comment below. I will be more than happy to assist you in your path to getting things done.

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.