Make String a Subsequence Using Cyclic Increments

This is the LeetCode problem number 2825. Cyclic increment This is when you increase an entity by an amount and when you reach the end you circle back to start and continue the count. If a is increased cyclicly by 1, we will get b. If a is increased cyclicly by 2, we will get c. But if z is increased cyclicly by 1, we get a. By 2 we will get b. String increaseCyclic (String str, int index) { char ch = str.charAt(index); char newch = (char) ((ch - 'a' + 1) % 26 + 'a'); return str.substring(0, index) + newChar + str.substring(index + 1); }Subsequence String str1 is said to contain the subsequence of str2 if we can delete some characters from str1 to get str2. During this deletion we are not allowed to disturb the relative order of chars in the str1. A code to check if str1 contains subsequence str2. We can iterate over all the characters of str1 sequencely and check if all the letters are there as in str2. boolean isSubsequence(String str1, String str2) { int p1 = 0; int p2 = 0; while (p1 < str1.length() && p2 < str2.length()) { if (str1.charAt(p1) == str2.charAt(p2)) { p2++; } p1++; } return p2 == str2.length(); }Solution The problem asks us that we are allowed to cyclic increase any number of chars in str1. And check whether we are able to say str1 will contain a subsequence of str2. We can solve this problem by just merging both the problems. Instead of checking just the characters equality, we can add an additional check on character of str1 after increasig it cyclicly. public boolean canMakeSubsequence(String str1, String str2) { int p1 = 0; int p2 = 0; while (p1 < str1.length() && p2 < str2.length()) { char cyclicCh = (char) ((str1.charAt(p1) - 'a' + 1) % 26 + 'a'); if (str1.charAt(p1) == str2.charAt(p2) || cyclicCh == str2.charAt(p2)) { p2++; } p1++; } return p2 == str2.length(); }

Downloading a single file from 2 independent apps

Understanding the problem Let's say you have a very large log file. And you want to create an app that can analyze this file and generate insights. Also, let's say you want to create an another app that can simulate the work by reading the logs one-by-one. Both these apps are dependent on the same log file. Now, there are 2 scenarios.App1 starts, downloads the file and then App2 starts. App1 starts, downloading the file and App2 starts while the download is incomlete.The first scenario is easy to deal with. We can check the md5sum of the local file and the file on the server. If they match, nothing to worrry about. If they don't then we can have a complex logic to determine the life of the old log file and decide accordingly. The second scenario is conflicting one and this we can solve in code. The second scenario can also happen when the same app is ran twice simultaneously. Both the instances will start downloading the same file and this will create a havoc. Solution The idea is to have an identifier that an app has already started the download and is still downloading the resouce. If the first app has started the download, then wait for the first app to complete the download and then only start the application. For accomplishing this, we generally use file locking mechanism. Download with file locking The process is modified to first create a lock file with extension .lock. This lock file signifies that a download is already in progress. If this lock file exists then wait for the download to complete by the second app. The lock file will have processid_threadid as identifier. This is useful in checking the race condition that can happen while writing the file. public static void downloadFileWithLock(String filePath) { File lockFile = new File(filePath + ".lock"); // Check if the file is being downloaded by another app // If it is being downloaded by an another app then wait for the download to finish // Else proceed with the download if (lockFile.exists()) { waitForDownloadToFinish(lockFile); } else { int processID = (int) ProcessHandle.current().pid(); String identifier = thread + "_" + processID; String contents = String.valueOf(identifier); writeToFile(lockFile, contents); // May be due to race condition, the file is already downloaded by another app // Check if this process started the download String savedIdentifier = readFromFile(lockFile); if (identifier.equals(savedIdentifier)) { // Download the file System.out.println(thread + " - Downloading file..."); File downloadFile = new File(filePath); try { RandomAccessFile randomAccessFile = new RandomAccessFile(downloadFile, "rw"); randomAccessFile.write("Very important works".getBytes()); Thread.sleep(5000); } catch (IOException e) {} catch (InterruptedException e) {} System.out.println(thread + " - File downloaded successflly."); } else { waitForDownloadToFinish(lockFile); } if (lockFile.exists()) { lockFile.delete(); } } }The Utilities method - waitFoDownloadToFinish, readFromFile and writeToFile are as follows. private static void writeToFile(File file, String contents) { try { Files.write(file.toPath(), contents.getBytes()); } catch (IOException e) { e.printStackTrace(); } } private static String readFromFile(File file) { try { return new String(Files.readAllBytes(file.toPath())); } catch (IOException e) { e.printStackTrace(); } return null; } private static void waitForDownloadToFinish(File lockFile) { System.out.println(thread + " - File is already being downloaded by another app. Wait for it to finish."); while (lockFile.exists()) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(thread + " - File download completed."); }Now you can create 2 new apps that will call this method and we will run the apps simultaneously. public class App1 { public static void main(String[] args) { String filePath = "downloaded_file.txt"; FileDownloadUtil.downloadFileWithLock(filePath); System.out.println(Thread.currentThread().getName() + " - App1 starting operation..."); } }public class App2 { public static void main(String[] args) { String filePath = "downloaded_file.txt"; FileDownloadUtil.downloadFileWithLock(filePath); System.out.println(Thread.currentThread().getName() + " - App2 starting operation..."); } }Outputs # For App1 main - Downloading file... main - File downloaded successfully. main - App1 starting operation...# For App2 main - File is already being downloaded by another app. Wait for it to finish. main - File download completed. main - App2 starting operation...App1 started downloading the file and thus App2 waited for the download to complete. After the download completes, both the apps resumed its operations. Conclusion and improvements This is just a basic code that lays the foundation of file locking mechanism for downloading a file simultaneously by multiple apps. This code is not a production ready code. A more complete solution should handle scenarios like downloads in chunks, resume functionality with unexpected shutdowns and other edge cases.

Reflection API in Java

Where is this used? This is used to analyze/modify the behaviour of a class at runtime. Using this, you can view or change the private/public fields at wish (without exposing any getter/setter). Personally, I have used this in one of our projects at GreyOrange to write unit test cases. Using this in main code is a big no-no as it exposed you critical fields to the world. Main Class Let's create a main class for which we will write some test cases. But we want to test some private fields for which we don't have a direct getter. The idea is to use reflection api to access such fields and fetch their current value or modify them if required. Here is a Duck class which has 3 fields of which 1 is static. Each time a duck class is created count which is the static field is increased by one. Each duck has an associated name and age. public class Duck { private String name; private int age; private static int count = 0; public Duck(String name, int age) { this.name = name; this.age = age; count++; } public static boolean canCreateMoreDucks() { return count < 10; } public String getName() { return name; } public boolean canDrinkAlcohol() { return age >= 18; }Test Class -- uses reflection API Change the value of a private field inside a class Field and getDeclaredField are used to access a variable. Using setAccessible as true will expose any private fields which can be manipulated. @Test public void testDuckCanDrinkAlcohol() { Duck duck = new Duck("Donald", 5); assertEquals("Donald", duck.getName()); assertFalse(duck.canDrinkAlcohol()); // change age and check if duck can drink alcohol // But I don't want to create a setter for this // Use reflection API to change the age try { Class<Duck> duckClass = Duck.class; Field ageField = duckClass.getDeclaredField("age"); ageField.setAccessible(true); ageField.setInt(duck, 20); } catch (Exception e) { e.printStackTrace(); assert false; } assertTrue(duck.canDrinkAlcohol());}Get the value of a static private variable in a class A static field can be accessed in the similar way. @Test public void testDuckCanCreateMoreDucks() { // Instead of creating more ducks // I will use reflection API to change the count Duck duck = new Duck("Donald", 5); assertTrue(Duck.canCreateMoreDucks()); // Also assert count was 1 // But I don't want to create a getter for this try { Class<Duck> duckClass = Duck.class; Field countField = duckClass.getDeclaredField("count"); countField.setAccessible(true); // Don't need to pass an instance as count is static Object countObject = countField.get(null); int count = (int) countObject; assertEquals(1, count); } catch (Exception e) { e.printStackTrace(); assert false; } }Change the value of a static private variable in a class You can use setInt to change the value of the Field. @Test public void testDuckCannotCreateMoreDucks() { // Instead of creating more ducks // I will use reflection API to change the count Duck duck = new Duck("Donald", 5); // change count to 10 try { Class<Duck> duckClass = Duck.class; Field countField = duckClass.getDeclaredField("count"); countField.setAccessible(true); countField.setInt(null, 10); } catch (Exception e) { e.printStackTrace(); assert false; } assertFalse(Duck.canCreateMoreDucks());}