here is the maven dependency.
<!--utils For Random Number / String generation:: https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
Code:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.RandomStringUtils;
/**
* a common utils class to generate random alphanumerics and project specific
* strings
*
*/
public class CommonUtils {
/**
* Method to generate random alpha numeric string of size 10
*
* @return
*/
public static String getRandomAlphaNumeric() {
return RandomStringUtils.randomAlphanumeric(10);
}
/**
* Method to generate random alphabet string of size 10
*
* @return
*/
public static String getRandomAlphabetic() {
return RandomStringUtils.randomAlphabetic(10);
}
/**
* Method to generate random numeric string of size 10
*
* @return
*/
public static String getRandomNumeric() {
return RandomStringUtils.randomNumeric(10);
}
/**
* Method to generate random numeric from the given max and min numbers
*
* @param max
* @param min
* @return
*/
public static int getRandomNumeric(int max, int min) {
Random rand = new Random();
int randomNum = rand.nextInt(max) + min;
return randomNum;
}
/**
* Method to generate random dates for checkin and checkout
*
* @return map of string, string
*/
public static HashMap<String, String> getDates() {
HashMap<String, String> map = new HashMap<String, String>();
int i = getRandomNumeric(285, 1);// checkin date
int j = getRandomNumeric(14, 1);// checkout date
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); // date format
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, i); // Adding i days
String checkinDate = sdf.format(c.getTime());
map.put("CHECKIN", checkinDate);
c.add(Calendar.DATE, j); // Adding j days
String checkoutDate = sdf.format(c.getTime());
map.put("CHECKOUT", checkoutDate);
return map;
}
/**
* Method to generate random email id
*
* @return
*/
public static String getRandomEmailId() {
return "John" + RandomStringUtils.randomNumeric(10) + ".Smith@test.com";
}
/**
* Method to convert given millsecs to hours,min,secs and milli secs
*
* @param millis
* @return
*/
public static String timeConversion(long millis) {
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
String strMilli = TimeUnit.MILLISECONDS.toMillis(millis) % TimeUnit.MINUTES.toMillis(1) + "";
hms = hms + ":" + strMilli;
return hms;
}
}
No comments:
Post a Comment