Monday, September 5, 2016

JAVA 17 - Unique username example

As promised last time, with our theory covered over, I'm going to take you through a couple of additional examples to help you learn.

Today I'm looking at a very useful recipe I use both in Selenium Webdriver and in Monkey Tamper.

In a lot of projects you need a unique username when registering an account.  Generally I have a very disposable attitude to accounts - I like to use them, set as I want, then throw them away.

But typically you need a unique username - I know friends who will use a random generator, but that always has potential to go bad.



The getUniqueName will return a unique username specified by the Unix time in milliseconds.

I use the method System.currentTimeMillis() to get the number of milliseconds since January 1st 1970.  Note I have to use a long integer type for this.

Obviously I've not covered that method, but like you might have to, I used Google to find out what kind of library/methods are available.  I don't think there's a single textbook out there, even one of these, which covers everything you'd need!



Google is great as is StackOverflow - it can show you how the command works, or you might be able to find an example.

I then define the character sequence,

CharSequence css = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";

This is essentially an array of characters.  I find the length of this array by using css.length() which is similar to the .size() method we've used for ArrayLists.

I repeatedly perform a modulus calculation on the Unix time, dividing by the length of my character sequence.  This gives me any remainder, which I look up in the sequence to give me a character.

I build up a string of these characters as I find the modulus, then actually divide my Unix time, until it's all done.  This turns the time into a handy character sequence ... so for instance ...




I typically append a "User_" in front of this string.  For my system, I get an email for every registered user, so I can backtrace to find any accounts I've created quite easily.

This really useful piece of code can be found here on Github.

No comments:

Post a Comment