How can I generate random emails using Selenium with Java?
I was looking here in StackOverflow but I haven't found the answer to this.
I have tried with this, but it didn't help.
public class registerClass{
public static void main(String[] args) {
System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
String baseUrl = " ";
driver.get(baseUrl);
driver.manage().window().maximize();
driver.findElement(By.id("cboxClose")).click();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.id("login")).click();
driver.findElement(By.xpath("/html/body/div[2]/div[1]/div/div[1]/div[2]/a[1]")).click();
driver.findElement(By.id("register.firstName")).sendKeys("Karla");
driver.findElement(By.id("register.paternalLastName")).sendKeys("Perez");
driver.findElement(By.id("register.maternalLastName")).sendKeys("castro");
driver.findElement(By.id("register.email")).sendKeys("castro9999#gmail.com");
//driver.close();
}
}
You need random string generator. This answer I stole from here.
protected String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 10) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
Call it as getSaltString()+"#gmail.com" in you code
You can create a method for generating the unique id
public static String getUniqueId() {
return String.format("%s_%s", UUID.randomUUID().toString().substring(0, 5), System.currentTimeMillis() / 1000);
}
And then use this method with the hostname which you need
public static String generateRandomEmail() {
return String.format("%s#%s", getUniqueId(), "yourHostName.com");
}
Another solution:
Add dependency for javafaker.Faker https://github.com/DiUS/java-faker
import com.github.javafaker.Faker;
public static String randomEmail() {
Faker faker = new Faker();
return faker.internet().emailAddress();
}
Try this method
/**
* #author mbn
* #Date 05/10/2018
* #Purpose This method will generate a random integer
* #param length --> the length of the random emails we want to generate
* #return method will return a random email String
*/
public static String generateRandomEmail(int length) {
log.info("Generating a Random email String");
String allowedChars = "abcdefghijklmnopqrstuvwxyz" + "1234567890" + "_-.";
String email = "";
String temp = RandomStringUtils.random(length, allowedChars);
email = temp.substring(0, temp.length() - 9) + "#testdata.com";
return email;
}
You can also use MockNeat. A simple example the library would be:
String email = mock.emails().val();
// Possible Output: icedvida#yahoo.com
Or if you want to generate emails from specific domains:
String corpEmail = mock.emails().domain("startup.io").val();
// Possible Output: tiptoplunge#startup.io
This is my solution for the random email generator.
//randomestring() will return string of 8 chars
import org.apache.commons.lang3.RandomStringUtils;
public String randomestring()
{
String generatedstring=RandomStringUtils.randomAlphabetic(8);
return(generatedstring);
}
//Usage
String email=randomestring()+"#gmail.com";
//For Random Number generation
////randomeNum() will return string of 4 digits
public static String randomeNum() {
String generatedString2 = RandomStringUtils.randomNumeric(4);
return (generatedString2);
}
If you don't mind adding a library, Generex is great for test data.
https://github.com/mifmif/Generex
Add this to your pom.xml if you are using maven, otherwise check the link above for other options.
<dependency>
<groupId>com.github.mifmif</groupId>
<artifactId>generex</artifactId>
<version>1.0.2</version>
</dependency>
Then:
// we have to escape # for some reason, otherwise we get StackOverflowError
String regex = "\\w{10}\\#gmail\\.com"
driver.findElement(By.id("emailAddressInput"))
.sendText(new Generex(regex).random());
It uses a regular expression to specify the format for the random generation. The regex above is generate 10 random word characters, append #gmail.com. If you want a longer username, change the number 10.
If you want to generate a random mobile number for say, Zimbabwe (where I live):
String regex = "2637(1|3|7|8)\\d{7}";
This library has saved me so many hours.
Here's a way to do it in Kotlin:
object EmailGenerator {
private const val ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyz" + "1234567890" + "_-."
#Suppress("SpellCheckingInspection")
fun generateRandomEmail(#IntRange(from = 1) localEmailLength: Int, host: String = "gmail.com"): String {
val firstLetter = RandomStringUtils.random(1, 'a'.toInt(), 'z'.toInt(), false, false)
val temp = if (localEmailLength == 1) "" else RandomStringUtils.random(localEmailLength - 1, ALLOWED_CHARS)
return "$firstLetter$temp#$host"
}
}
Gradle file :
// https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
implementation 'org.apache.commons:commons-lang3:3.7'
Related
I've created a method in JAVA in order to do the same thing of an existing PHP function, that is: convert an arbitrarily large number from any base to any base.
The java method is working fine and I can convert numbers from one base to another and then convert it back, but the resulted strings are different from the PHP function. This is a problem to me, because I want to convert a number in PHP and then convert it back in JAVA.
For example, lets convert the number 998765;43210;9999;2 from Base11 with alphabet 0123456789; to Base21 with alphabet 0123456789ABCDEFGHIJK in PHP and JAVA:
Result of the example in PHP:
convBase("998765;43210;9999;2", "0123456789;", "0123456789ABCDEFGHIJK") = "GJK7K6B2KKGKK96"
Result of the example in JAVA:
convBase("998765;43210;9999;2", "0123456789;", "0123456789ABCDEFGHIJK") = "1B0EJAJ0IG3DABI"
I would like the results to be the same, so I could convert a number in PHP and convert it back in JAVA.
I think that the problem can be character encoding, but I don't know how to solve it.
PHP function and test:
<?php
function convBase($numberInput, $fromBaseInput, $toBaseInput)
{
if ($fromBaseInput==$toBaseInput) return $numberInput;
$fromBase = str_split($fromBaseInput,1);
$toBase = str_split($toBaseInput,1);
$number = str_split($numberInput,1);
$fromLen=strlen($fromBaseInput);
$toLen=strlen($toBaseInput);
$numberLen=strlen($numberInput);
$retval='';
if ($toBaseInput == '0123456789')
{
$retval=0;
for ($i = 1;$i <= $numberLen; $i++)
$retval = bcadd($retval, bcmul(array_search($number[$i-1], $fromBase),bcpow($fromLen,$numberLen-$i)));
return $retval;
}
if ($fromBaseInput != '0123456789')
$base10=convBase($numberInput, $fromBaseInput, '0123456789');
else
$base10 = $numberInput;
if ($base10<strlen($toBaseInput))
return $toBase[$base10];
while($base10 != '0')
{
$retval = $toBase[bcmod($base10,$toLen)].$retval;
$base10 = bcdiv($base10,$toLen,0);
}
return $retval;
}
header('Content-Type: text/html; charset=utf-8');
$number = "998765;43210;9999;2";
$fromBase = "0123456789;";
$toBase = "0123456789ABCDEFGHIJK";
$converted = convBase($number, $fromBase, $toBase);
$back = convBase($converted, $toBase, $fromBase);
echo "Number: ".$number."<br>";
echo "Converted: ".$converted."<br>";
echo "Back: ".$back."<br>";
?>
JAVA method and test:
import java.math.BigInteger;
public class ConvBase{
public static String convBase(String number, String fromBaseInput, String toBaseInput){
if (fromBaseInput.equals(toBaseInput))
return number;
BigInteger fromLen = new BigInteger(""+fromBaseInput.length());
BigInteger toLen = new BigInteger(""+toBaseInput.length());
BigInteger numberLen = new BigInteger(""+number.length());
if(toBaseInput.equals("0123456789")){
BigInteger retval = BigInteger.ZERO;
for(int i=1; i<=number.length(); i++){
retval = retval.add(
new BigInteger(""+fromBaseInput.indexOf(number.charAt(i-1))).multiply(
fromLen.pow(numberLen.subtract(new BigInteger(""+i)).intValue())
//pow(fromLen, numberLen.subtract(new BigInteger(""+i)))
)
);
}
return ""+retval;
}
String base10 = fromBaseInput.equals("0123456789") ? number : convBase(number, fromBaseInput, "0123456789");
if(new BigInteger(base10).compareTo(toLen) < 0)
return ""+toBaseInput.charAt(Integer.parseInt(base10));
String retVal = "";
BigInteger base10bigInt = new BigInteger(base10);
while(!base10bigInt.equals(BigInteger.ZERO)){
retVal = toBaseInput.charAt(base10bigInt.mod(toLen).intValue()) + retVal;
base10bigInt = base10bigInt.divide(toLen);
}
return ""+retVal;
}
public static void main(String[] args) {
String number = "98765;43210;9999;2";
String fromBase = "0123456789;";
String toBase = "0123456789ABCDEFGHIJK";
String converted = ConvBase.convBase(number, fromBase, toBase);
String back = ConvBase.convBase(converted, toBase, fromBase);
System.out.println("Number = "+number);
System.out.println("Converted = "+converted);
System.out.println("Back = "+back);
System.exit(0);
}
}
There is a typo in your test case. Both programs seem to be correct, or at least consistent.
Your Java variant converts "98765;43210;9999;2" while your PHP program converts "998765;43210;9999;2". Note the two nines at the beginning. When I changed the number I got the following output:
Number = 998765;43210;9999;2
Converted = GJK7K6B2KKGKK96
Back = 998765;43210;9999;2
which is consistent with the output of the PHP version.
In a class (Java8), I have a String representing an HTTP URL, e.g. String str1="http://www.foo.com/bar", and another string containing a request URI e.g. str2="/bar/wonky/wonky.html".
What is the fastest way in terms of code execution to determine if str2 is within the context of str1 (e.g. the context is /bar) and then construct the complete url String result = "http://www.foo.com/bar/wonky/wonky.html"?
Well I don't know if there is a faster way to just use String.indexOf(). Here is an approach that I think covers the example you gave (demo):
public static boolean overlap(String a, String b_context) {
//Assume the a URL starts with http:// or https://, the next / is the start of the a_context
int root_index = a.indexOf("/", 8);
String a_context = a.substring(root_index);
String a_host = a.substring(0, root_index);
return b_context.startsWith(a_context);
}
Here is a function that uses the same logic but to combine the two urls if they overlap or throw an exception if they don't
public static String combine(String a, String b_context) {
//Assume the a URL starts with http:// or https://, the next / is the start of the a_context
int root_index = a.indexOf("/", 8);
String a_context = a.substring(root_index);
String a_host = a.substring(0, root_index);
if(b_context.startsWith(a_context)) {
return a_host + b_context;
} else {
throw new RuntimeException("urls do not overlap");
}
}
And here is an example of using them
public static void main(String ... args) {
System.out.println(combine("http://google.com/search", "/search?query=Java+String+Combine"));
System.out.println(combine("http://google.com/search", "/mail?inbox=Larry+Page"));
}
I'm creating program like parcel machine. I'm connected to mysql db.
As you can see I have field "final int orderPassword". I would like to generate it automatically by method which I put at the end of this topic.
public static void post() throws Exception{
final int parcelID = 2;
final int clientMPNumber = 777777777;
final int orderPassword = 1234;
try{
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO Parcels.Orders (parcelID, clientMPNumber, orderPassword) VALUES ('"+parcelID+"', '"+clientMPNumber+"', '"+orderPassword+"')");
posted.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally{
System.out.println("Insert completed");
}
}
Below is method which I want to put instead of "final int orderPassword".
public static int generatePass(){
Random generator = new Random();
int orderPassword = generator.nextInt(9000)+1000;
return orderPassword;
}
How can I do it?
Given that your method is in the same class oder package, simply change
final int orderPassword = 1234;
to
final int orderPassword = generatePass();
Remark: for better random passwords, you could use some library like https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html
I suggest to have a more secure password, a String password in particular.
Create an array of char to contain numbers and letters (and special chars optional).
Randomly get -for example- 6 chars from 6 random indices. (Note, it can be any length, not necessarily 6, according to the field size in your DB).
public static String generatePassword(int length){
char source[] = "A0b1C2d3E4f5G6h7I8j9K0l1M2n3O4p5Q6r7S8t9U0v1W2x3Y4z5".toCharArray();
Random generator = new Random();
String password ="";
for(int i=0; i<length; i++){
password += source[generator.nextInt(source.length)];
}
return password;
}
And to use it, you just do:
String orderPassword = generatePassword(6); // of length 6 for example
Output Samples:
36Ynv3
13Kvp5
4A4117
0zlSS3
vr5625
So I have a Test where I am filling out a form. What I want is to run this test multiple times and each time to use different input values such as a different name. I think I can use some kind of word list to do this? But I'm not sure exactly how to go about it.
.completePersonalAddressDetails("04/06/2017","NONE","Mr","Ohaye",
"04/05/1985","Tester","British","123 boombastic avenue","G412LQ")
public NewStartPage completePersonalAddressDetails(String startDate, String NINumber,
String title, String Name, String DOB, String LastName,
String nationality, String addressLine, String postcode) {
helper.switchToMainFrame();
startDateInput.sendKeys(startDate);
helper.sleep();
payrollCompanyLookUp.click();
helper.switchToLookUpFrame();
firstPayrollCompany.click();
helper.switchToMainFrame();
payrollCompanySelectButton.click();
niNumberInput.clear();
niNumberInput.sendKeys(NINumber);
Select selectTitle = new Select(titleSelect);
selectTitle.selectByValue(title);
firstNameInput.sendKeys(Name);
maritalStatusInput.click();
helper.switchToLookUpFrame();
helper.sleep();
maritalStatusDivorced.click();
helper.switchToMainFrame();
maritalStatusSelectButton.click();
DOBInput.sendKeys(DOB);
lastNameInput.sendKeys(LastName);
Select selectNationality = new Select(nationalitySelect);
selectNationality.selectByVisibleText(nationality);
genderInput.click();
helper.switchToLookUpFrame();
helper.sleep();
genderMale.click();
helper.switchToMainFrame();
genderSelect.click();
helper.sleep();
addressLineInput.sendKeys(addressLine);
postcodeInput.sendKeys(postcode);
driver.switchTo().defaultContent();
return PageFactory.initElements(driver, NewStartPage.class);
}
You can create a method to generate random text. See mine below
public String generateRandomName(int length) {
char[] chars =abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String randomString = sb.toString();
return randomString;
}
Then when you want to fill out a form you can do the following:
String firstName = ClassName.generateRandomName(9); // 9 Characters long
driver.findElement(By.xpath("Your xpath")).sendKeys(firstName);
You can call that method for wherever you want to call a random string of text. Hope it helps.
So, since dynamic variables aren't a thing in Java, and if statements will be horribly unwieldy, was looking for help converting this code block into a more concise one.
I looked into hashmaps, and they just didn't seem quite right, it's highly likely I was misunderstanding them though.
public String m1 = "Name1";
public String m1ip = "192.1.1.1";
public String m2 = "Name2";
public String m2ip = "192.1.1.1";
public String req;
public String reqip;
... snip some code...
if (requestedMachine == 1)
{ req = m1; reqip = m1ip;}
else if (requestedMachine == 2)
{ req = m2; reqip = m2ip;}
else if (requestedMachine == 3)
{ req = m3; reqip = m3ip;}
else if (requestedMachine == 4)
{ req = m4; reqip = m4ip;}
else if (requestedMachine == 5)
{ req = m5; reqip = m5ip;}
requestedMachine is going to be an integer, that defines which values should be assigned to req & reqip.
Thanks in advance.
Define a Machine class, containing a name and an ip field. Create an array of Machine. Access the machine located at the index requestedMachine (or requestedMachine - 1 if the number starts at 1):
Machine[] machines = new Machine[] {
new Machine("Name1", "192.1.1.1"),
new Machine("Name2", "192.1.1.1"),
...
}
...
Machine machine = machines[requestedMachine - 1];
First, create a Machine class:
class Machine {
String name;
String ip;
//Constructor, getters, setters etc omitted
}
Initialize an array of Machines:
Machine[] machines = ... //initialize them with values
Get the machine corresponding to requestedMachine:
Machine myMachine = machines[requestedMachine];
This is a great candidate for an enum:
/**
<P>{#code java EnumDeltaXmpl}</P>
**/
public class EnumDeltaXmpl {
public static final void main(String[] ingo_red) {
test(MachineAction.ONE);
test(MachineAction.TWO);
test(MachineAction.THREE);
test(MachineAction.FOUR);
}
private static final void test(MachineAction m_a) {
System.out.println("MachineAction." + m_a + ": name=" + m_a.sName + ", ip=" + m_a.sIP + "");
}
}
enum MachineAction {
ONE("Name1", "192.1.1.1"),
TWO("Name2", "292.2.2.2"),
THREE("Name3", "392.3.3.3"),
FOUR("Name4", "492.4.4.4"),
FIVE("Name5", "592.5.5.5");
public final String sName;
public final String sIP;
private MachineAction(String s_name, String s_ip) {
sName = s_name;
sIP = s_ip;
}
}
Output:
[C:\java_code\]java EnumDeltaXmpl
MachineAction.ONE: name=Name1, ip=192.1.1.1
MachineAction.TWO: name=Name2, ip=292.2.2.2
MachineAction.THREE: name=Name3, ip=392.3.3.3
MachineAction.FOUR: name=Name4, ip=492.4.4.4
Thee best choice you have is to build an array of machines with IP, Name etc..then you only need to find the machine required into the array.
public class Machine(){
private String name, ip;
public Machine(String name, String ip){
this.name=name;
// You can check a valid ip
this.ip=ip;
}}
public class Machines(){
private Machine[] machines;
private int number_of_machines;
public Machines(){
//define number_of_machines for your array and length of itself
}}
main()
Machine[] Machines = new Machine[number_of_machines];
Machine m1 = new Machine(String name, String ip);
.
.
.
Machine mn = new Machine(String name, String ip);
int number=5;
for(int i=0; i<number_of_machines; i++){
if (machines[number]<number_of_machines){
System.out.println("There is no machine with that number");
}else if (machines[number]==number_of_machines-1){
System.out.println("That is the choosen machine");
}
}
}
If your id values are not necessarily integers or if they are not a continuous sequence from 0 forward, you could also use a HashMap. Something like
HashMap<Integer, Machine> machines = new HashMap<>();
machines.put(1, machine1);
machines.put(7, machine7);
...
to get the desired value
Machine machine7 = machines.get(7);
You can replace the key with a String or whatever you like if needed. Your id values also do not need to go 0,1,2,3,4,5, ... as they need to if you are going with an array.