Java - Best Practice - FAQ

1] Here myListConsistOfSQL is the List<String> which consist of SQL scripts for execution
PreparedStatement ps=null;
try{
        conn=getMyDBConnection();
for(String sql: myListConsistOfSQL) {
        ps = conn.prepareStatement(sql);
        ps.addBatch();
        ps.executeBatch();
    }
} Catch(Exception e) {
    throw new e;
} finally {
    if(ps!=null) {
        ps.close();
    }
  if(conn!=null) {
        conn.close();
    }
}


2] Map object to print the key and values using for each loop
myDataMap.forEach((key, value) -> log.info("Details:: " + key + ":" + value));
myDataList.forEach(msg -> log.info(msg));

3] Logger message utility class to hold details in list
import java.util.ArrayList;
import java.util.List;

public class MessagesUtil { 
  private static List<String> msgList = new ArrayList<String>();
  public static List<String> getMsgList() {
      return msgList;
  }
  public static void setMsgList(String p_msg){
      msgList.add(p_msg);
  }
  public static void clearMsgs(){
      msgList.clear();
  }
}


4] JSON object to iterate and print list of values in UI
$.each(resp, function(key, value) {
        var result = '';
        //Loop JSON object to table
            result += '<tr>';
            result += '<td>' + key + '</td>';
            result += '<td>' + value + '</td>';
            result += '</tr>';
        //Appending row to result
        $('#tdBody').append(result);
});

html have tdbody reference as below
<tr id="tdBody"> </tr>


5] Reset Select Option list (Dropdown value to default select value)
function checkSelectedType(selVal) {
    global_varType = selVal;
    $("#TYPE option[value='']").attr('selected', true);
    $('.textTitle).text('Please Select');
}

html code:
<select id="TYPE" name="OperationType" onchange="checkSelectedType(this)">
        <option value="" selected="selected">Please Select</option>
        <option value="RED_VALUE">Red Color</option>
        <option value="BLUE_VALUE">Blue Color</option>
</select>


6] Reload the page after completion of successful
function reloadPage() {
    window.location.reload();
}


7] Allow only csv and excel file to be uploaded from upload component
function validateFileName() {
    var fileUpload = document.getElemenById("upload_file_component");
    var regEx = /^([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx|.xsv)$/;

    if(!regEx.test(fileUpload.value.toLowerCase())) {
        return false;
    } else {
        return true;
    }
}

html code:
<input id="upload_file_component" name="upload_file_component" type="file" accept=".xls, .xlsx, .csv" />


8] Ajax call to show loading icon and hide when finished
var form = $('#myForm')[0];
var data = new FormData(form);

$.ajax({type="post, enctype: 'multipart/form-date',
               url: '/backend_API_Method_call',
                data: data,
                processData: false, contentType: false, cache: false,
                beforeSend: function() {
                    showLoading();
                },
                success: function(msg) {
                    var resp = JSON.parse(msg);
                    hideLoading();
                    
                    $.each(resp, function(key, value) {
                       //filter out data based on specific value set from response value
                     if(value.includes("Error") || value.includes("Exception")){
                        //do something
                      }
                            var result = '';
                            //Loop JSON object to table
                            result += '<tr>';
                            result += '<td>' + key + '</td>';
                            result += '<td>' + value + '</td>';
                            result += '</tr>';
                            //Appending row to result
                            $('#tdBody').append(result);
                        });
                    },
                    error: function(e) {
                        hideLoading();
                        console.log('Error' , e);
                    }
                }

function showLoading(){
    $(#loader").show();
}

function hideLoading(){
    $(#loader").hide();
}

html code:
<div id="loader" class="loading" style="display:none;">&nbsp;</div>


9] Check is null or blank value
public static boolean isNullorBlank(String pVal) {
    return ((pVal == null) || (pVal.trim().length() == 0));
}


10] Generate IN query using Java-8 stream API from List values
List<String> inValues = Arrays.asList("Bhavin", "Patel");
String inQuery = inValues.stream().collect(Collectors.joining("','"," in ('","')"));
System.out.println("inQuery :: " + inQuery);

O/P:
inQuery ::  in ('Bhavin','Patel')

There are many use cases for this, Can be used in prepared query, SQL query or any filter cases.


11] Java-8+, To check the boolean condition using steam API
Refactored from traditional for loop to stream api. 
For example, we have a collection and need to check the boolean condition:
List<MyCode> charges = getMyCodes();
for(MyCode c: charges) {
  if(c.isResolved()) {
    c.printLabel();
  }
}
The functional approach let us refactor these lines to a single sentence:
rules.stream().filter(MyCode::isResolved)
              .forEach(MyCode::printLabel);


12] Alternatives to nested if - else conditions (Refactored)
What are the alternatives to the “if” statement?
1. Ternary notation: result = A ? B : C. If A true or not null return B else C.
private boolean invertBoolean(boolean b) {
  return b ? false : true;
}
private int getMinValue(int i, int j) {
  return (i < j) ? i : j;
}
2. Switch statement.
int i = 10;
switch (i) {
  case 5:
    System.out.println("i = 5");
    break;
  case 10:
    System.out.println("i = 10");
    break;
  default:
    System.out.println("i does not equals 5 or 10");
}


13] Combine two map data and take out unique data into third map 
import java.util.*;
import java.util.stream.Collectors; 

public class Main {
    public static void main(String[] args) {
        // Create two sample maps
        Map<String, List<Map<String, String>>> map1 = new HashMap<>();
        Map<String, List<Map<String, String>>> map2 = new HashMap<>(); 

        // Populate map1 and map2 with sample data (You should replace this with your data)
        List<Map<String, String>> list1 = new ArrayList<>();
        List<Map<String, String>> list2 = new ArrayList<>();

        Map<String, String> innerMap1 = new HashMap<>();
        innerMap1.put("key1", "value1");
        innerMap1.put("key2", "value2"); 

        Map<String, String> innerMap2 = new HashMap<>();
        innerMap2.put("key3", "value3");
        innerMap2.put("key4", "value4"); 

        list1.add(innerMap1);
        list2.add(innerMap2);
        map1.put("list1", list1);
        map2.put("list2", list2);
        // Combine map1 and map2 into a unique map using Java streams
        Map<String, List<Map<String, String>>> combinedMap = Stream.of(map1, map2)
                .flatMap(map -> map.entrySet().stream())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (existingValue, newValue) -> {
                            existingValue.addAll(newValue);
                            return existingValue;
                        },
                        HashMap::new
                ));

         // Print the combined map
        System.out.println(combinedMap);
    }
}


14] Singleton utility class creation - design pattern
public class MainClassUtil {
    private static final Logger log = LoggerFactory.getLogger(MainClassUtil.class);
    private static volatile MainClassUtil mainUtil;

    private MainClassUtil() {
    }

    public static MainClassUtil getInstance() {
        if (mainUtil == null) {
            synchronized (MainClassUtil.class) {
                if (mainUtil == null) {
                    mainUtil = new MainClassUtil();
                }
            }
        }
        return mainUtil;
    }
}


15] Async. Singleton utility class creation - For background processing
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * My Async. Utility Singleton class used for creating thread executer services pool
 */
public class MyAsyncUtil {
private static final Logger log = LoggerFactory.getLogger(MyAsyncUtil.class);
    private static volatile MyAsyncUtil myAsyncUtil;
    private MyAsyncUtil() {
    }
    /**
     * Get instance method for object creation
     * @return instance of MyAsyncUtil
     */
    public static MyAsyncUtil getInstance() {
        if (myAsyncUtil == null) {
            synchronized (MyAsyncUtil.class) {
                if (myAsyncUtil == null) {
                    myAsyncUtil = new MyAsyncUtil();
                    myAsyncUtil.initializeAsyncThreadPool();
                }
            }
        }
        return myAsyncUtil;
    }

    private ExecutorService executorService;
    
    private void initializeAsyncThreadPool(){
        //Initialize max thread pool size (default)
        int maxDefaultThreadCount = 25;
        try {
//READ_FROM_APP_PROPERTY_FILE -> Get from prop file external configured.
            maxDefaultThreadCount = <READ_VALUE_FROM_APP_PROPERTY_FILE>;
        } catch (MyException e) {
            //in case of error while reading custom object, setting default thread pool size.
            log.error("Error occured while reading value from property file {} : {}", <READ_VALUE_FROM_APP_PROPERTY_FILE>, e);
        }

        //setting daemon thread to true, so that when application closes daemon thread can be stopped by JVM.
        executorService = Executors.newFixedThreadPool(maxDefaultThreadCount, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setDaemon(true);
                return t;
            }
        });
        log.debug("My Asyc. has been initialized with thread pool size {}", maxDefaultThreadCount);
    }

    public ExecutorService getExecutorService() {
        return executorService;
    }
}

-> How to utilize above method in other classes
//Initialise
MyAsyncUtil myAsyncCall = MyAsyncUtil.getInstance();

//Executing any method/call in background
myAsyncCall.getExecutorService().execute(() -> {
try {
YourOperationMethodBackground(Param1, Param2);
} catch (Throwable e) {
log.error("Log error here message:",e);
}
});

public void YourOperationMethodBackground(Param1, Param2) {
// Your logic will come here
}

Comments

Popular posts from this blog

PUTTY - The server's host key is not cached in the registry cache

OIM-12c Installation - FMW - SOA - IDM

Apache Kafka - Zookeeper