From Hell To Heaven: Safeguarding your application – Part 1

Have you ever wondered how to safeguard your application when using the database and a cache like Redis? What if one of them is down? What should we do? These are questions that every developer should ask themselves when building an API that needs to be reliable 24/7.

In this guide, we will be configuring a cache error handler that will cover every scenario where Spring Cache annotations are used.

Building the cache error handler

The reason to build a custom error handler is simple: we want the application working even though the cache is down.

We will need to do two things: Implement the CacheErrorHandler interface and registering into our application. Below is the implementation of our class:

package com.jerieshandal.api.config; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.Cache; import org.springframework.cache.interceptor.CacheErrorHandler; @Slf4j public class CustomCacheErrorHandler implements CacheErrorHandler { @Override public void handleCacheGetError(RuntimeException e, Cache cache, Object o) { log.error(e.getMessage(), e); } @Override public void handleCachePutError(RuntimeException e, Cache cache, Object o, Object o1) { log.error(e.getMessage(), e); } @Override public void handleCacheEvictError(RuntimeException e, Cache cache, Object o) { log.error(e.getMessage(), e); } @Override public void handleCacheClearError(RuntimeException e, Cache cache) { log.error(e.getMessage(), e); } } Read more...

From Hell To Heaven: Increase app’s performance with Redis

Welcome to my new series “From Hell To Heaven“. These series will be about different cases of programmers dealing with issues that anyone can find in a typical day. In this first post, we will be implementing Redis as a second level cache layer using Spring Boot.

Introduction

I have been working on a couple of projects and encountered several performance issues. This issue relied mostly on reading the same data multiple times in the same endpoint. Using second layer cache is a common solution to this issue and that’s what we are going to do today! You will see how easy it will be to integrate Redis as a cache layer using Spring boot.

What is Redis?

Redis is an in-memory data structure used as a database or cache. Being in-memory provides a huge benefit in performance; reading and writing are way faster than persisting to disk. It also provides a way of persisting data utilizing RDB and AOF, making it perfect to keep the data when restarting the server.

Implementation

Dependencies and Configuration

Your project will need spring-boot-starter-data-redis dependency in order to work properly with Spring Boot. Then we need to configure Redis and the cache, which is fairly easy to do it by taking advantage of Spring Boot’s auto configuration as shown in the following segment:

spring.redis.url=redis://user:password@example.com:6379 spring.redis.host=localhost # Redis server host. spring.redis.password= # Login password of the redis server. Leave empty if no password spring.redis.port=6379 # Redis server port. spring.cache.type=redis spring.cache.redis.cache-null-values=true # Allow caching null values. spring.cache.redis.key-prefix=project_key # Key prefix. spring.cache.redis.time-to-live=60000ms # Entry expiration. By default the entries never expire. spring.cache.redis.use-key-prefix=true # Whether to use the key prefix when writing to Redis. Read more...

Binary Search | Search Algorithm

The theory

A binary search algorithm is a search algorithm that uses the concept of divide and conquer in order to find a target value’s position. Basically, this search algorithm compares the target value with the middle element of the collection.

If it is equal, return the position. If it is not equal, then we will need to check if the value is either greater or less than the target value. This is to know what side of the collection we need to split.

Binary Search Requirements

There’s a condition applied to the binary search array, which is that the array must be sorted. This is because it uses the value (in our case an integer), to compare and check if the selected position has the target value or check where to go.

Binary Search Array Algorithm

Implementation

First things first, we will create our binary search class with the search methods.

public class BinarySearch {

public int search(int[] array, int number) {
return search(array, number, 0, array.length);
}

private int search(int[] array, int target, int start, int end) {
int mid = (start + end) / 2;

if (end < start) {
return -1;
}

if (array[mid] == target) {
return mid;
} else if (array[mid] > target) {
return search(array, target, 0, mid - 1);
} else {
return search(array, target, mid + 1, end);
}
}
}

Read more...

Modifying and Updating a JAR File| Java

A Brief Introduction…

It all started when a co-worker asked for help when trying to update an IP Address of a java API, however, he only had the JAR file available. With another co-worker, we dug up the internet and tried to find a way to do this, and we finally did. I thought of sharing what we acquire for any future help.

Requirements

In order to do any of the operations mentioned in the title, you will need to have java and JDK installed, a desired jar you want to modify, and basic knowledge of commands for the terminal. In order to get the .java file from the JAR, I would recommend a program called JD-GUI. You will just need to open the jar file, and look for a desired file and save it.

JAR Process

For this tutorial, we will be using the linked list jar we created in another tutorial. As we open the jar file with JD-GUI, I will choose to add another constructor in the Node.java class.

jd-gui-node

After saving it, we will be opening and modifying the java class with your favorite Java Editor. If you noticed, a jar is composed of .class files, which contains pure byte code and we wouldn’t be able to read it that easy. We will convert the .java file to .class through the command line and with the javac command: javac Node.java

javac

Note: I am following the same folder structure as the JAR file. linkedlist>Node.class.

Until now, we have modified and generated the Node.class file, so we are just missing update the current file in the JAR. In order to do this, we will need to use the jar uvf command: jar uvf LinkedList.jar linkedlist/Node.class. The -u in the command means that we will be updating/inserting a specific file inside the JAR.

jd-uvr-java

Ta-da! You just have modified and update a JAR file in a very simple way. Please open the jar file using JD-GUI again and check if the changes were done correctly.

jd-gui-working

If you wish to extract a specific file without requiring JD-GUI, it will be with using the -x argument within the jar command: jar xvf LinkedList.jar linkedlist/Node.class .

I hope you have learned how to modify and update any JAR file. Please let me know if you have any other further questions or comments.

Linked List | Data Structures

A brief introduction

Linked List is a linear collection of objects, which is composed of nodes pointing to the next node. Each node contains a value and a reference to the next node in the sequence. Most of the operations applied in a linked list (add, remove, search, etc.) will require sequencial scanning most of the time.

single-linked-list
As you can notice, each node will always have a pointer to the next node and a value, this is called a single linked list. If a node has a link to the previous and to the next one, it is called a double linked list or a circular linked list.

Implementation

The first step will be creating a node class:

public class Node<T>{

    private Node next;
    private T value;

    public Node(){
        
    }
    
    public Node(T value){
        this.value = value;
    }
    
    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }
}

This is a POJO (Plain Old Java Object) of a Node class, which contains a value and another Node that will be the “Next” node. If you ask yourself about the “T” I have in there, I am declaring the Node class as Generic, enabling the option to choose what datatype to use. Now, we will be creating varios operations used, starting with the add.

public class MyLinkedList<T>{

private Node head;
private static int counter;

public void add(T value){

if (head == null) {
head = new Node(value);
} else {
Node temp = new Node(value);
Node current = head;

while (current.getNext() != null) {
current = current.getNext();
}

current.setNext(temp);
}

counter++;
}
}
Read more...

Creating a new project | Android Tutorials #2

In the previous lesson, we learn about the different kind of IDEs that exist for android development. Now, we will be using Android Studio to create a project and review each file and folder created, and thinks to consider.

Before we begin…

If you have not downloaded Android Studio, you can download it from here. We will also need JDK (Java Development Kit), which you can download from here, and we need Android SDK, which is already included with the Android Studio. After downloading and installing, we are more than ready to begin this lesson.

Creating a new project

After opening Android Studio for the first time, it will display a window where you can create or open a project, if it doesn’t appear let’s just create a new one by going to File > New > New Project, a screen like the following will appear:

s1

Under “Application Name”, we will be writing how our application will be named and displayed as an app when we run it in our phones, I will be calling my application: “TextDisplayer”, and under “Company Domain”, we will write any name so that the package name follows this pattern: “com.companyname.appname”. Hit next after setting the project location path.

The next step will be choosing the targeted devices, phone, tablets, android wear, TV, auto, and Glass. You can select multiple devices, this will depend in your app’s focus. We will be selecting the Phone and Tablet only and now we need to select the minimum SDK for our app. We will be considering various factors: the lower the minimum SDK, the less features you will get, however, we will be targeting more devices. You will notice that there’s a percentage provided by the IDE, which allows you to check an estimate of the devices that runs in that specific version and later. I will be choosing API 19: Android 4.4 (KitKat), considering I will be running this in my phone (connected with USB Debugging On).

s2

Now for the last step, we can choose an activity from the ones that are listed or add no activity. These activities are pre-configured and comes with Android Studio as templates to avoid “reinventing the wheel” and fasten the process of creating one of the listed activities. We will be looking at most of the activities later on, but now we will be choosing an empty activity, which means a page with absolutely nothing in it. You choose a name for that activity and click finish. This is how we can create a project in Android Studio.

s3

Let the gradle process finish and let’s start checking what files has been created. Under “manifests”, we can find AndroidManifest.xml, which basically functions as the configuration file for activities (all activities will be declared here), permissions (Internet, Contacts, etc.), and other related to the application. The java folder contains all the java classes and activitiesthat the application will use, right now we only have MainActivity, and we can find the JUnit Test Package. We will also find a resource folder that contains all the layouts, drawables, icons, and strings used by the application. If you ask yourself what’s under Gradle Scripts, you are very curious! Gradle Scripts contains properties, settings, dependencies, android SDK version, minimun SDK Version, and many other app-related settings. For example, you can add more dependencies like Google Gson, etc. in build.gradle (app).

s4

What’s Next?

We have seen how to create a project, went through each folder and check what’s inside (not into detail), and we could also run the project by clicking play/run icon, requiring a smartphone with USB Debugging On or an emulated device.

In the next tutorial, we are going to detail the Activity class and define every method that you could use, XML files like the layouts, strings, etc.. Theory is always good!