I'm having a string with delimiter : which has two tokens (old & new token). I've two scenarios - I may get
- only old token
oldToken-NmH0FKDKiITkIDDopLDkDD - old and new token
oldToken-NmH0FKDKiITkIDDokDDsOxMdUU2qPnRxKiY:newToken-IdsfdWeRrrfziTjHNGfyKfK9YCoEsy6nTDI
Step 1:
To identify old and new token, the string is appended with oldToken- and newToken-. I'm checking if the string contains both old and new tokens, if yes get the newToken value or else get the oldtoken value. To get the actual value, I'm removing this appended string based on condition
splitResult[1].replaceAll("newToken-", ""))
Step 2: Once I get the token value, checking this token exist in the map or else make an external call one by one by passing the token.
My challenge here is I'm duplicating replaceAll in a lot of places, how to get rid of this. Or is there any better way to refactor the below code, sorry I'm new to Java so please excuse me
Please find the code below:
public class Main {
public static void main(String[] args) {
// Scenario 1: This contains both the token
String myKey = "oldToken-NmH0FKDKiITkIDDokDDsOxMdUU2qPnRxKiY:newToken-IdsfdWeRrrfziTjHNGfyKfK9YCoEsy6nTDI";
// Scenario 2: This contains only one token
// String myKey = "oldToken-NmH0FKDKiITkIDDopLDkDD";
String[] splitResult = myKey.split(":");
System.out.println(test(splitResult));
}
private static String test(String[] splitResult) {
// Scenario 1: Map with value
Map<String, String> myMap = new HashMap<>();
myMap.put("NmH0FKDKiITkIDDokDDsOxMdUU2qPnRxKiY", "user1");
myMap.put("IdsfdWeRrrfziTjHNGfyKfK9YCoEsy6nTDI", "user2");
// Scenario 2: Empty Map
// Map<String, String> myMap = new HashMap<>();
String cache = null;
if (splitResult.length >= 2) {
if (splitResult[1].contains("newToken-") && splitResult[0].contains("oldToken-")) {
cache = myMap.get(splitResult[1].replaceAll("newToken-", ""));
}
} else {
cache = myMap.get(splitResult[0].replaceAll("oldToken-", ""));
}
// If no value in cache, make an external call with both the token
if (cache == null) {
String request = null;
for (String getVal : splitResult) {
if (getVal.contains("oldToken")) {
request = getVal.replaceAll("oldToken-", "");
System.out.println("request: " + request);
// Make an external call
} else if (getVal.contains("newToken")) {
request = getVal.replaceAll("newToken-", "");
System.out.println("request: " + request);
// Make an external call
}
}
}
return cache;
}
}