import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Utilities {
/**
*
* @param directory File directory that will be checked
* If directory does not exist it will be created
*/
public static void makeDirIfItDoNotExist(File directory) {
if (!directory.exists()) {
directory.mkdir();
}
}
/**
* Look for port using ServerSocket
* Once port is found, socket is closed.
*
* @return int: port available for use
*/
public static int getAvailablePort() {
int port = 0;
try {
ServerSocket serverSocket = new ServerSocket(0);
port = serverSocket.getLocalPort();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
return port;
}
/**
*
* @return A String representation of the project directory with '/' appended to it
* Sample: /Users/username/Desktop/FacebookPOC/
*/
public static String getProjectDirectory() {
return System.getProperty("user.dir") + "/";
}
/**
*
* @param fileName = String you want to name the log file
* @return A String representation of the log file name with '/' prefix and date suffix
* Pattern: /filename_date_month_year-hour:minutes:seconds
* Sample: /fileName_06_02_2021-06:03:51
*/
public static String generateFileName(String fileName) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd_MM_yyyy-hh:mm:ss");
LocalDateTime now = LocalDateTime.now();
return "/" + fileName + "_" + dtf.format(now);
}
}