Wednesday, 29 April 2020

Check whether given character present in string or not

Using ‘indexOf’ method, we can check whether given character is present in string or not. ‘indexOf()’ method return -1, if given character is not present in the string, else it return the index of the first occurrence of the character in the string.

Example
private static boolean isCharExist(String str, char ch) {
         if (str == null) {
                  throw new IllegalArgumentException("String can't be null");
         }

         return str.indexOf(ch) != -1;
}

Find the following working application.

App.java
package com.sample.app;

public class App {

 private static boolean isCharExist(String str, char ch) {
  if (str == null) {
   throw new IllegalArgumentException("String can't be null");
  }

  return str.indexOf(ch) != -1;
 }

 public static void main(String args[]) {
  String str = "Hello World";

  char ch = 'H';
  System.out.println("is " + ch + " exists in " + str + " : " + isCharExist(str, ch));

  ch = 'o';
  System.out.println("is " + ch + " exists in " + str + " : " + isCharExist(str, ch));

  ch = 'a';
  System.out.println("is " + ch + " exists in " + str + " : " + isCharExist(str, ch));
 }

}

Output
is H exists in Hello World : true
is o exists in Hello World : true
is a exists in Hello World : false


You may like

Delete all the files in a directory

Write a program to delete all the files in a directory recursively (Not the directories).

Input Directory structure
1
├── 2
│   ├── 2.1
│   │   └── b.txt
│   └── c.txt
└── 3
    └── d.txt

3 directories, 3 files

Once you run the application, it should delete all the files and corresponding directory structure will change like below.

Output directory structure
1
├── 2
│   └── 2.1
└── 3

Code Snippet
private static void deleteAllFiles(File dir) {
         for (File file : dir.listFiles()) {
                  if (file.isDirectory()) {
                           deleteAllFiles(file);
                           continue;
                  }
                  System.out.println("Deleting file : " + file.getAbsolutePath());
                  file.delete();

         }
}

Find the following working application.

App.java
package com.sample.app;

import java.io.File;

public class App {

 private static void deleteAllFiles(String filePath) {
  File file = new File(filePath);

  if (!file.isDirectory()) {
   return;
  }

  deleteAllFiles(file);
 }

 private static void deleteAllFiles(File dir) {
  for (File file : dir.listFiles()) {
   if (file.isDirectory()) {
    deleteAllFiles(file);
    continue;
   }
   System.out.println("Deleting file : " + file.getAbsolutePath());
   file.delete();

  }
 }

 public static void main(String args[]) {
  String folderPath = "/Users/Shared/1";

  deleteAllFiles(folderPath);
 }

}

Output
Deleting file : /Users/Shared/1/3/d.txt
Deleting file : /Users/Shared/1/2/2.1/b.txt
Deleting file : /Users/Shared/1/2/c.txt

You may like

Convert CharSequence to String

Approach 1 : Using toString() method.
charSequence.toString()

Approach 2: Using String.valueOf()
String.valueOf(charSequence);

Approach 3: Using StringBuilder.
StringBuilder builder = new StringBuilder();
String result = builder.append(charSequence).toString();

Find the below working application.

App.java
package com.sample.app;

public class App {

 private static String getString_approach1(CharSequence charSequence) {
  if (charSequence == null) {
   return null;
  }
  return charSequence.toString();
 }

 private static String getString_approach2(CharSequence charSequence) {
  if (charSequence == null) {
   return null;
  }
  return String.valueOf(charSequence);
 }

 private static String getString_approach3(CharSequence charSequence) {

  if (charSequence == null) {
   return null;
  }

  StringBuilder builder = new StringBuilder();
  String result = builder.append(charSequence).toString();
  return result;
 }

 public static void main(String args[]) {
  CharSequence charSequence = "Hello World";

  String str1 = getString_approach1(charSequence);
  String str2 = getString_approach2(charSequence);
  String str3 = getString_approach3(charSequence);

  System.out.println("str1 : " + str1);
  System.out.println("str2 : " + str2);
  System.out.println("str3 : " + str3);
 }

}

Output
str1 : Hello World
str2 : Hello World
str3 : Hello World



You may like

Javassist: Create new interface at run time

Using ‘makeInterface’ method, you can create new interface.

Step 1: Get an instance of ClassPool.
ClassPool pool = ClassPool.getDefault();

Step 2: Create an interface using makeInterface method.
CtClass ctClass = pool.makeInterface("com.sample.app.interface.Arithmetic");

Step 3: Define methods
CtMethod sum = new CtMethod(CtClass.intType, "sum", new CtClass[] { CtClass.intType, CtClass.intType }, ctClass);
sum.setBody("return $1 + $2;");

CtMethod areaOfCircle = new CtMethod(CtClass.doubleType, "areaOfCircle", new CtClass[] { CtClass.doubleType },ctClass);

Step 4: Add methods to the interface.
ctClass.addMethod(sum);
ctClass.addMethod(areaOfCircle);

Find the below working application.

App.java
package com.sample.app;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

public class App {

 public static void main(String args[]) throws Exception {
  ClassPool pool = ClassPool.getDefault();

  CtClass ctClass = pool.makeInterface("com.sample.app.interface.Arithmetic");

  CtMethod sum = new CtMethod(CtClass.intType, "sum", new CtClass[] { CtClass.intType, CtClass.intType },
    ctClass);
  sum.setBody("return $1 + $2;");

  CtMethod areaOfCircle = new CtMethod(CtClass.doubleType, "areaOfCircle", new CtClass[] { CtClass.doubleType },
    ctClass);

  ctClass.addMethod(sum);
  ctClass.addMethod(areaOfCircle);

  ctClass.writeFile("/Users/Shared/assistDemos");

 }
}

Run App.java.

You can observe Arithmetic.class file is generated at folder /Users/Shared/assistDemos.
$tree /Users/Shared/assistDemos
/Users/Shared/assistDemos
└── com
    └── sample
        └── app
            └── interface
                └── Arithmetic.class

4 directories, 1 file

Open Arithmetic.class file in decompiler to see the source code.



Previous                                                    Next                                                    Home

Javassist: Add new method and invoke it for an existing class

Follow below steps to add and invoke new method.

Step 1: Get an object of ClassPool.
ClassPool classPool = ClassPool.getDefault();

Step 2: Get CtClass object for given class.
CtClass ctClass = classPool.get("com.sample.app.Test");

Step 3: Define and add new method to CtClass instance.
CtMethod newmethod = CtNewMethod.make("public void print() { System.out.println(\"Hey are you there\"); }",ctClass);
ctClass.addMethod(newmethod);
   
Step 4: Publish byte code changes.
ctClass.toClass();

Step 5: Call the added method using reflection.   
Test test = new Test();
Method method = test.getClass().getMethod("print", new Class[] {});
method.invoke(test, new Object[] {});

Find the below working application.

Test.java
package com.sample.app;

public class Test {

}

App.java
package com.sample.app;

import java.lang.reflect.Method;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;

public class App {

  public static void main(String args[]) throws Exception {
    ClassPool classPool = ClassPool.getDefault();

    CtClass ctClass = classPool.get("com.sample.app.Test");

    CtMethod newmethod = CtNewMethod.make("public void print() { System.out.println(\"Hey are you there\"); }",
        ctClass);
    ctClass.addMethod(newmethod);
    
    ctClass.toClass();
    
    Test test = new Test();
    Method method = test.getClass().getMethod("print", new Class[] {});
    method.invoke(test, new Object[] {});
  }
}

Run App.java, you will get below message in console.

Hey are you there



Previous                                                    Next                                                    Home

Javassist: Modify type of instance field

It is a two-step process.
a.   Remove the field
b.   Create a filed with same name with different type

Follow below step-by-step procedure to modify type of a field.

Step 1: Get ClassPool instance.
ClassPool classPool = ClassPool.getDefault();

Step 2: Get CtClass instance.
CtClass pointClass = classPool.get("com.sample.app.model.Point");

Step 3: Remove the field from CtClass instance.
CtField toBeDeleted = pointClass.getField("x");
pointClass.removeField(toBeDeleted);

Step 4: Create field with same with different data type.
CtField xField = new CtField(CtClass.doubleType, "x", pointClass);
xField.setModifiers(Modifier.PUBLIC);

Step 5: Add new field to the class.
pointClass.addField(xField);

Step 6: Publish modified byte code
pointClass.toClass();

Find the below working application.

Point.java
package com.sample.app.model;

public class Point {
    public int x;
    public int y;

}

App.java
package com.sample.app;

import java.lang.reflect.Field;

import com.sample.app.model.Point;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.Modifier;

public class App {

    public static boolean set(Object object, String fieldName, Object fieldValue) {
        Class<?> clazz = object.getClass();
        while (clazz != null) {
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                field.set(object, fieldValue);
                return true;
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
        return false;
    }

    @SuppressWarnings("unchecked")
    public static <V> V get(Object object, String fieldName) {
        Class<?> clazz = object.getClass();
        while (clazz != null) {
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                return (V) field.get(object);
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
        return null;
    }

    public static void main(String args[]) throws Exception {
        ClassPool classPool = ClassPool.getDefault();

        CtClass pointClass = classPool.get("com.sample.app.model.Point");

        CtField toBeDeleted = pointClass.getField("x");
        pointClass.removeField(toBeDeleted);

        CtField xField = new CtField(CtClass.doubleType, "x", pointClass);
        xField.setModifiers(Modifier.PUBLIC);
        pointClass.addField(xField);

        // Publish modified byte code
        pointClass.toClass();

        pointClass.writeFile("/Users/Shared/javassist");
        Point point = new Point();

        set(point, "x", 1.2345);
        Object value = get(point, "x");

        System.out.println("Value of x is " + value);
    }

}

Run App.java, you will see below message in console.
Value of x is 1.2345

You can observe that Point.class file is created at /Users/Shared/javassist.

$tree /Users/Shared/javassist
/Users/Shared/javassist
└── com
    └── sample
        └── app
            └── model
                └── Point.class

4 directories, 1 file

Open Point.class in any java decompiler to see the source code.



Previous                                                    Next                                                    Home

Monday, 27 April 2020

Javassist: Add methods to the new class

Follow below steps to add new method to a class.

Step 1: Create an instance of ClassPool.
ClassPool pool = ClassPool.getDefault();

Step 2: Create new class using makeClass method
CtClass ctClass = pool.makeClass("com.sample.app.model.Point");

Step 3: Create a method using CtMethod.
CtMethod getX = CtNewMethod.make(Modifier.PUBLIC, CtClass.intType, "getX", null, null, "return x;", ctClass);

Step 4: Add getX method to the class.
ctClass.addMethod(getX);

Find the below working application.

App.java
package com.sample.app;

import java.lang.reflect.Modifier;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewMethod;

public class App {

 public static void main(String args[]) throws Exception {
  ClassPool pool = ClassPool.getDefault();

  CtClass ctClass = pool.makeClass("com.sample.app.model.Point");

  CtField xField = new CtField(CtClass.intType, "x", ctClass);
  xField.setModifiers(Modifier.PRIVATE);

  CtField yField = new CtField(CtClass.intType, "y", ctClass);
  yField.setModifiers(Modifier.PRIVATE);

  ctClass.addField(xField);
  ctClass.addField(yField);

  CtMethod getX = CtNewMethod.make(Modifier.PUBLIC, CtClass.intType, "getX", null, null, "return x;", ctClass);
  CtMethod getY = CtNewMethod.make(Modifier.PUBLIC, CtClass.intType, "getY", null, null, "return y;", ctClass);

  CtMethod setX = new CtMethod(CtClass.voidType, "setX", new CtClass[] { CtClass.intType }, ctClass);
  setX.setBody("{ x = $1; }");

  CtMethod setY = new CtMethod(CtClass.voidType, "setY", new CtClass[] { CtClass.intType }, ctClass);
  setY.setBody("{ y = $1; }");

  ctClass.addMethod(getX);
  ctClass.addMethod(getY);
  ctClass.addMethod(setX);
  ctClass.addMethod(setY);

  Object obj = ctClass.toClass().newInstance();
  System.out.println("Class Name : " + obj.getClass());

  ctClass.writeFile("/Users/Shared/assistDemos");

 }
}

Run App.java, you will get below messages in console.

Class Name : class com.sample.app.model.Point

You can observe Point.class file is generated at folder /Users/Shared/assistDemos.
$ tree /Users/Shared/assistDemos
/Users/Shared/assistDemos
└── com
    └── sample
        └── app
            └── model
                └── Point.class

4 directories, 1 file

Open the .class file in java decompiler to see the source code.



Previous                                                    Next                                                    Home

Java: Remove a field from class

Follow below steps to remove a field from class.

Step 1: Get ClassPool instance.
ClassPool classPool = ClassPool.getDefault();

Step 2: Get CtClass instance.
CtClass pointClass = classPool.get("com.sample.app.model.Point");

Step 3: Get CtField instance that refer to the field that we want to delete.
CtField toBeDeleted = pointClass.getField("x");

Step 4: Remove the field.
pointClass.removeField(toBeDeleted);

Step 5: Publish modified byte code
pointClass.toClass();

Previous                                                    Next                                                    Home

Implement re-try-catch

Write code such that, you should execute some code snippet. If you got any error while executing the code snippet, sleep for 100 milliseconds and retry ‘N’ times.

Following snippet implements above functionality.
public void retryAndExecuteErrorProneCode(int noOfTimesToRetry, CodeSnippet codeSnippet, int sleepTimeInMillis)
  throws InterruptedException {

 int currentExecutionCount = 0;
 boolean codeExecuted = false;

 while (currentExecutionCount < noOfTimesToRetry) {
  try {
   codeSnippet.errorProneCode();
   System.out.println("Code executed successfully!!!!");
   codeExecuted = true;
   break;
  } catch (Exception e) {
   // Retry after 100 milliseconds
   TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis);
   System.out.println(e.getMessage());
  } finally {
   currentExecutionCount++;
  }
 }

 if (!codeExecuted)
  throw new RuntimeException("Can't execute the code within given retries : " + noOfTimesToRetry);
}

Find the below working application.

CodeSnippet.java
package com.sample.app.lambdas;

public interface CodeSnippet {

 public void errorProneCode();
}

RetryUtil.java
package com.smaple.app.utils;

import java.util.concurrent.TimeUnit;

import com.sample.app.lambdas.CodeSnippet;

public class RetryUtil {
 public void retryAndExecuteErrorProneCode(int noOfTimesToRetry, CodeSnippet codeSnippet, int sleepTimeInMillis)
   throws InterruptedException {

  int currentExecutionCount = 0;
  boolean codeExecuted = false;

  while (currentExecutionCount < noOfTimesToRetry) {
   try {
    codeSnippet.errorProneCode();
    System.out.println("Code executed successfully!!!!");
    codeExecuted = true;
    break;
   } catch (Exception e) {
    // Retry after 100 milliseconds
    TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis);
    System.out.println(e.getMessage());
   } finally {
    currentExecutionCount++;
   }
  }

  if (!codeExecuted)
   throw new RuntimeException("Can't execute the code within given retries : " + noOfTimesToRetry);
 }

}

App.java
package com.sample.app;

import java.util.Random;

import com.smaple.app.utils.RetryUtil;

public class App {

 public static void main(String args[]) throws InterruptedException {
  RetryUtil retryUtil = new RetryUtil();
  retryUtil.retryAndExecuteErrorProneCode(3, () -> {
   Random rand = new Random();

   int randVal = rand.nextInt(50);

   if (randVal <= 10) {
    return;
   }

   throw new RuntimeException("Service Unavailable");
  }, 100);
 }

}

Sample Output 1
Service Unavailable
Service Unavailable
Service Unavailable
Exception in thread "main" java.lang.RuntimeException: Can't execute the code within given retries : 3
         at com.smaple.app.utils.RetryUtil.retryAndExecuteErrorProneCode(RetryUtil.java:30)
         at com.sample.app.App.main(App.java:11)


Sample Output 2
Code executed successfully!!!!

Sample Output 3
Service Unavailable
Service Unavailable
Code executed successfully!!!!




You may like