CodeByAkram: Java 8
Showing posts with label Java 8. Show all posts
Showing posts with label Java 8. Show all posts

Read Files from classpath or resource folder and subfolder - Java

 The below code shows hot to read the list of resources(files) from a classpath folder and subfolder.

Below is the example code



import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.util.*;

public class ReadResourceFiles {

    public static void main(String[] args) throws IOException {
        List resourceFolderFiles = getResourceFolderFiles("static");
        resourceFolderFiles.stream().filter(f -> f.endsWith(".json")).forEach(System.out::println);
    }

    static List getResourceFolderFiles(String folder) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        URL url = loader.getResource(folder);
        String path = url.getPath();
        File file = new File(path);
        List files = new ArrayList<>();
        if(file.isDirectory()){
            try {
                Files.walk(file.toPath()).filter(Files::isRegularFile)
                        .filter(f-> f.toFile().getName().toLowerCase().endsWith(".json"))
                        .forEach(f -> files.add(f.toFile().getPath()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else if(file.getName().toLowerCase().endsWith(".json")){
            files.add(file.getPath());
        }
        return files;
    }
}

How to use / implement OWASP ESAPI Logger in Java

Before going further lets talk about Log Forging or JVM Log Forging. 

Log Forging

According to OWASP , writing invalidated logs can allow attackers to forge log or inject malicious content in log file. Log forging is when attackers tries to add/modify the log content by exploring the security loopholes of application.

Lets understand the log forging by an example.


private void printLog(String amount) {
logger.info("Amount credited in account Rs. {}" + amount);
}
above code will print the logs like:

Amount credited in account Rs. 500

 Now suppose attacker provide the input \n\n Amount debited in account Rs.500

Amount credited in account Rs. 500

Amount debited in account Rs.500

So, attacker forged the logs by making a fake or forge entry in log.


Avoid directly embedding user input in log files when possible. Sanitize untrusted data used to construct log entries by using safe logging mechanism such as OWASP ESAPI logger, which will automatically remove unexpected carriage returns. So, to prevent this, we use use ESAPI Logger mechanism.

Here is the dependency of ESAPI: 

<dependency>

<groupId>org.owasp.esapi</groupId>

<artifactId>esapi</artifactId>

<version>2.2.2.0</version>

</dependency>

We can encode the logs using ESAPI‘s Encoder method and interface:


    public String encode(String message) {
    message = message.replace( '\n' ,  '_' ).replace( '\r' , '_' )
      .replace( '\t' , '_' );
    message = ESAPI.encoder().encodeForHTML( message );
    return message;
}
How to use / implement OWASP ESAPI Logger in Java





Multi threading using Executor Services in Java

 The ExecutorService interface, executes tasks in parallel in background and represents an asynchronous execution mechanism. The ExecutorService create and maintain the reusable thread pool.


How to create ExecutorService?

To create ExecutorService, you can use Executors factory to create the instance of ExecutorService. Lets see some examples.


 There are diffrent way to execute or submit the task with ExecutorService.
  1. submit(Runnable)
  2. submit(Callable)
  3. execute(Runnable)
  4. invokeAny(...)
  5. invokeAll(...)
Lets go through with the example to run multiple treads with ExecutorService.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HTMLUnitMultipleThreads {

	public static void main(String[] args) {

		int threadSize = 5;
		ExecutorService executor = Executors.newFixedThreadPool(threadSize);
		for (int i = 0; i < threadSize; i++) {
			executor.submit(new MultiThreadingService());
		}
	}
}

public class MultiThreadingService implements Runnable {

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println("Thread Name = " + Thread.currentThread().getName());
		}

	}

}

Java 8 Lambda Comparator

Lets se how we can sort the object by using java 8 lambda comparator. For this let take a Employee class.

Java 8 Lambda Comparator, codebyakram

public class Employee {
    private String name;
    private int salary;
 
    // standard constructors, getters/setters, equals and hashcode
}

1. Classic sort (without lambda)

Comparator< Employee > bySalary = new Comparator< Employee >() {
  @Override
  public int compare(Employee o1, Employee o2) {
   return o1.getSalary().compareTo(o2.getSalary());
  }
 };
2. Lambda expression equivalent.

 Comparator< Employee > bySalary = 
  (Employee o1, Employee o2)->o1.getSalary().compareTo(o2.getSalary());

You may also like to read What do you mean by Aspect, Join Point, Advice?