"insert into" random number to mysql db - java

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

Related

Generate random emails with Selenium

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'

JAVA - How do I write variables to a text file with a specific style?

String cDate = getDate();
String cClientName = getClientName();
String cRN = getRN();
int cPackage = getPackage();
int cDB = getDB(cPackage);
int cPeriod = getPeriod(cRN);
boolean cIC = getIC();
double mCharge = getMCharge(cPackage, cDB, cPeriod, cRN, cIC);
saveContract(cDate, cClientName, cRN, cPackage, cDB, cPeriod, cIC, mCharge);
I have these variables and want to be able to save these variables to a text file as such:
15-Sep-2015_TAB_ Client name_TAB_Reference number_TAB_Package
My question is: How do I write these variables to a text file (which I want to read from the file later) using a tab to seperate each variable?
You can achieve this using the varargs parameter. This would give output for mergeParams("test1", "test2", "test3"); as "test1 test2 test3" values separated by "\t" ie tabs
private static void mergeParams(String... params) {
for(int i = 0; i < params.length; i++) {
System.out.print(params[i]+"\t");
}
}

Selenium Webdriver - How can I randomise a test to input new details every time?

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.

Java Storing Multiple Rows From Select Queries

This is actually a re-do of an older question of mine that I have completely redone because my old question seemed to confuse people.
I have written a Java program that Queries a database and is intended to retrieve several rows of data. I have previously written the program in Informix-4GL and I am using a sql cursor to loop through the database and store each row into a "dynamic row of record". I understand there are no row of records in Java so I have ended up with the following code.
public class Main {
// DB CONNECT VARIABLE ===========================
static Connection gv_conn = null;
// PREPARED STATEMENT VARIABLES ==================
static PreparedStatement users_sel = null;
static ResultSet users_curs = null;
static PreparedStatement uinfo_sel = null;
static ResultSet uinfo_curs = null;
// MAIN PROGRAM START ============================
public static void main(String[] args) {
try {
// CONNECT TO DATABASE CODE
} catch(Exception log) {
// YOU FAILED CODE
}
f_prepare(); // PREPARE THE STATEMENTS
ArrayList<Integer> list_id = new ArrayList<Integer>();
ArrayList<String> list_name = new ArrayList<String>();
ArrayList<Integer> list_info = new ArrayList<String>();
ArrayList<String> list_extra = new ArrayList<String>();
try {
users_sel.setInt(1, 1);
users_curs = users_sel.executeQuery();
// RETRIEVE ROWS FROM USERS
while (users_curs.next()) {
int lv_u_id = users_curs.getInt("u_id");
String lv_u_name = users_curs.getString("u_name");
uinfo_sel.setInt(1, lv_u_id);
uinfo_curs = uinfo_sel.executeQuery();
// RETRIEVE DATA FROM UINFO RELATIVE TO USER
String lv_ui_info = uinfo_curs.getString("ui_info");
String lv_ui_extra = uinfo_curs.getString("ui_extra");
// STORE DATA I WANT IN THESE ARRAYS
list_id.add(lv_u_id);
list_name.add(lv_u_name);
list_info.add(lv_ui_info);
list_extra.add(lv_ui_extra);
}
} catch(SQLException log) {
// EVERYTHING BROKE
}
// MAKING SURE IT WORKED
System.out.println(
list_id.get(0) +
list_name.get(0) +
list_info.get(0) +
list_extra.get(0)
);
// TESTING WITH ARBITRARY ROWS
System.out.println(
list_id.get(2) +
list_name.get(5) +
list_info.get(9) +
list_extra.get(14)
);
}
// PREPARE STATEMENTS SEPARATELY =================
public static void f_prepare() {
String lv_sql = null;
try {
lv_sql = "select * from users where u_id >= ?"
users_sel = gv_conn.prepareStatement(lv_sql);
lv_sql = "select * from uinfo where ui_u_id = ?"
uinfo_sel = gv_conn.prepareStatement(lv_sql)
} catch(SQLException log) {
// IT WON'T FAIL COZ I BELIEEEVE
}
}
}
class DBConn {
// connect to SQLite3 code
}
All in all this code works, I can hit the database once, get all the data I need, store it in variables and work with them as I please however this does not feel right and I think it's far from the most suited way to do this in Java considering I can do it with only 15 lines of code in Informix-4GL.
Can anyone give me advice on a better way to achieve a similar result?
In order to use Java effectively you need to use custom objects. What you have here is a lot of static methods inside a class. It seems that you are coming from a procedural background and if you try to use Java as a procedural language, you will not much value from using it. So first off create a type, you can plop it right inside your class or create it as a separate file:
class User
{
final int id;
final String name;
final String info;
final String extra;
User(int id, String name, String info, String extra)
{
this.id = id;
this.name = name;
this.info = info;
this.name = name;
}
void print()
{
System.out.println(id + name + info + extra);
}
}
Then the loop becomes:
List<User> list = new ArrayList<User>();
try {
users_sel.setInt(1, 1);
users_curs = users_sel.executeQuery();
// RETRIEVE ROWS FROM USERS
while (users_curs.next()) {
int lv_u_id = users_curs.getInt("u_id");
String lv_u_name = users_curs.getString("u_name");
uinfo_sel.setInt(1, lv_u_id);
uinfo_curs = uinfo_sel.executeQuery();
// RETRIEVE DATA FROM UINFO RELATIVE TO USER
String lv_ui_info = uinfo_curs.getString("ui_info");
String lv_ui_extra = uinfo_curs.getString("ui_extra");
User user = new User(lv_u_id, lv_u_name, lv_ui_info, lv_ui_extra);
// STORE DATA
list.add(user);
}
} catch(SQLException log) {
// EVERYTHING BROKE
}
// MAKING SURE IT WORKED
list.get(0).print();
This doesn't necessarily address the number of lines. Most people who use Java don't interact with databases with this low-level API but in general, if you are looking to get down to the fewest number of lines (a questionable goal) Java isn't going to be your best choice.
Your code is actually quite close to box stock JDBC.
The distinction is that in Java, rather than having a discrete collection of arrays per field, we'd have a simple Java Bean, and a collection of that.
Some examples:
public class ListItem {
Integer id;
String name;
Integer info;
String extra;
… constructors and setters/getters ellided …
}
List<ListItems> items = new ArrayList<>();
…
while(curs.next()) {
ListItem item = new ListItem();
item.setId(curs.getInt(1));
item.setName(curs.getString(2));
item.setInfo(curs.getInfo(3));
item.setExtra(curs.getString(4));
items.add(item);
}
This is more idiomatic, and of course does not touch on the several frameworks and libraries available to make DB access a bit easier.

zerofill method using java

I want my textfield become like this “99999”
this is my code
while (rs.next()){
int s=rs.getInt("Number");
String num1 = String.valueOf(s);
String n = String.format("%05d",num1);
view.txtcustomernumber.setText(n);
}
why my txtcustomernumber(JTextField) always blank
Try this.
while (rs.next()){
int s=rs.getInt("Number");
String n = String.format("%05d",s);
view.txtcustomernumber.setText(n);
}
It might solve your problem.

Categories