Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts
Sunday, January 29, 2017
Saturday, October 22, 2016
DB details from properties file using Java
Reusuable class to get db details from properties file.
Now the helper function that reads from the property file and return the value from the property file.
Sunday, February 21, 2016
Cashless transaction with local Transport - part 3
package JavaSMSProject;
import java.net.*;
public class CopyOfSMSclass {
public void sendSMS(Integer amount, Integer bal, String recipient) {
try {
//String recipient = "918888899999"; // Receipietnt mobile number
String message = "Your account has been deducted with" + amount + "your current balance is" + bal;
String username = "xxx"; //Username that you have registered with OzekiNG
String password = "xxx"; // Password that you have registered with OzekiNG
String originator = "918888866666"; // Sender mobile number
String requestUrl = "http://127.0.0.1:9501/api?action=sendmessage&" +
"username=" + URLEncoder.encode(username, "UTF-8") +
"&password=" + URLEncoder.encode(password, "UTF-8") +
"&recipient=" + URLEncoder.encode(recipient, "UTF-8") +
"&messagetype=SMS:TEXT" +
"&messagedata=" + URLEncoder.encode(message, "UTF-8") +
"&originator=" + URLEncoder.encode(originator, "UTF-8") +
"&serviceprovider=HTTPServer0" +
"&responseformat=html";
//GSMModem1
URL url = new URL(requestUrl);
HttpURLConnection uc = (HttpURLConnection)url.openConnection();
System.out.println(uc.getResponseMessage());
uc.disconnect();
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
This class triggers SMS gateway and sends the information to the customer.
A basic application to work with SMS along with cashless transaction with local transport and it has few enhancements to work on.
Cashless transaction with local Transport - part 2
Readdatabase.class
package JavaSMSProject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadDatabase {
public void writeToExcel(String fileName, String uid, String amount) throws IOException {
Integer cellValue = 0;
Integer cellAmount = 0;
Integer bal = 0;
Integer phoneNumber = 0;
FileInputStream fsIP= new FileInputStream(new File(fileName));
XSSFWorkbook workbook = new XSSFWorkbook(fsIP);
XSSFSheet sheet = workbook.getSheetAt(0);
int count = sheet.getPhysicalNumberOfRows();
System.out.println(count);
List<String> list = new ArrayList<String>();
/*int size = list.size(); */
for(int i=0; i < count - 1; i++){
XSSFRow row1 = sheet.getRow(i + 1);
Cell cell1 = row1.getCell(0);
cellValue = (int)Math.round(cell1.getNumericCellValue());
System.out.println("UserId:" + cellValue);
String matchuid = cellValue.toString();
if(uid.equalsIgnoreCase(matchuid)){
Cell cell2 = row1.getCell(1);
cellAmount = (int)Math.round(cell2.getNumericCellValue());
System.out.println("Amount:" + cellAmount);
bal = cellAmount - Integer.parseInt(amount);
System.out.println("Bal remaning:" + bal);
Cell cell3 = row1.getCell(2);
phoneNumber = (int)Math.round(cell3.getNumericCellValue());
System.out.println("Phone number:" + phoneNumber);
cell2.setCellValue(bal.doubleValue());
CopyOfSMSclass sms = new CopyOfSMSclass();
sms.sendSMS(Integer.parseInt(amount), bal, phoneNumber.toString());
break;
}//if
//list.add(cell1.getStringCellValue());
}//for
System.out.println("Sorry no such user found");
fsIP.close();
try (FileOutputStream outputStream = new FileOutputStream(new File(fileName))) {
workbook.write(outputStream);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
package JavaSMSProject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadDatabase {
public void writeToExcel(String fileName, String uid, String amount) throws IOException {
Integer cellValue = 0;
Integer cellAmount = 0;
Integer bal = 0;
Integer phoneNumber = 0;
FileInputStream fsIP= new FileInputStream(new File(fileName));
XSSFWorkbook workbook = new XSSFWorkbook(fsIP);
XSSFSheet sheet = workbook.getSheetAt(0);
int count = sheet.getPhysicalNumberOfRows();
System.out.println(count);
List<String> list = new ArrayList<String>();
/*int size = list.size(); */
for(int i=0; i < count - 1; i++){
XSSFRow row1 = sheet.getRow(i + 1);
Cell cell1 = row1.getCell(0);
cellValue = (int)Math.round(cell1.getNumericCellValue());
System.out.println("UserId:" + cellValue);
String matchuid = cellValue.toString();
if(uid.equalsIgnoreCase(matchuid)){
Cell cell2 = row1.getCell(1);
cellAmount = (int)Math.round(cell2.getNumericCellValue());
System.out.println("Amount:" + cellAmount);
bal = cellAmount - Integer.parseInt(amount);
System.out.println("Bal remaning:" + bal);
Cell cell3 = row1.getCell(2);
phoneNumber = (int)Math.round(cell3.getNumericCellValue());
System.out.println("Phone number:" + phoneNumber);
cell2.setCellValue(bal.doubleValue());
CopyOfSMSclass sms = new CopyOfSMSclass();
sms.sendSMS(Integer.parseInt(amount), bal, phoneNumber.toString());
break;
}//if
//list.add(cell1.getStringCellValue());
}//for
System.out.println("Sorry no such user found");
fsIP.close();
try (FileOutputStream outputStream = new FileOutputStream(new File(fileName))) {
workbook.write(outputStream);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Cashless transaction with local Transport
The goal of this project is to send SMS to people who have been registered with an local transport organization where they pay amount in advance and travel through out the year as long as they have balance available.
For this project I have used OzekiNG to simulate SMS.
Here are the class files:
Deduct balance.class
package JavaSMSProject;
import java.io.IOException;
import java.util.Scanner;
public class Deductbalance {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter the user id:");
String user_id = in.next();
//in.close();
Scanner in2 = new Scanner(System.in);
System.out.println("Enter the amount:");
String amount = in2.next();
//sin2.close();
String workingDir = System.getProperty("user.dir");
String fileName = workingDir + "\\resources\\Localtransportdatabase.xlsx";
//String path =
ReadDatabase rd = new ReadDatabase();
rd.writeToExcel(fileName, user_id, amount);
}
}
Other classes are in next posts.
For this project I have used OzekiNG to simulate SMS.
Here are the class files:
Deduct balance.class
package JavaSMSProject;
import java.io.IOException;
import java.util.Scanner;
public class Deductbalance {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter the user id:");
String user_id = in.next();
//in.close();
Scanner in2 = new Scanner(System.in);
System.out.println("Enter the amount:");
String amount = in2.next();
//sin2.close();
String workingDir = System.getProperty("user.dir");
String fileName = workingDir + "\\resources\\Localtransportdatabase.xlsx";
//String path =
ReadDatabase rd = new ReadDatabase();
rd.writeToExcel(fileName, user_id, amount);
}
}
Other classes are in next posts.
Saturday, November 14, 2015
Converting java code to executable jar file through command prompt
Assume we have set of java files written using
an IDE. To conver the file as executable jar file through command prompt and run it across machines. Here are the
steps to follow:
§ Create a new folder . Eg: java2jar
§ Create another folder in the newly created folder and copy
all the .class files that are required for the program to execute.
Eg:
java2jar> src> copy all the files here.
§ Create a folder in the main folder and name it as lib or
anything of your choice and copy all the dependable jar files. This is optional and if you have dependable jars.
Eg:
java2jar>>lib>>copy all jar files here.
§ Open command prompt in Windows click on windows icon , type
ctrl + R and then enter cmd .
§ Navigate to the path where you have created the new folder
that has all .class files.
>>cd C:\Users\lenovo\Desktop\java2jar
§ Type path and enter the path for jre available in the
machine.In my machine it is available in the following location.
>>cd C:\Users\lenovo\Desktop\java2jar>path
C:\Program Files\Java\jre1.8.0_45\bin
§ Create new text document in java2jar(my folder name) and
rename it as manifest.txt file.
§ Open manifest.txt and type as follows:
Class-Path:
lib\jar1.jar lib\jar2.jar lib\jar3.jar #continue entering all jar files
available
Main-Class:src\main.class
#Enter the main class file that has main() method.
If you don't have dependable jars then skip Class-Path and enter only Main-Class.
If you don't have dependable jars then skip Class-Path and enter only Main-Class.
§ Save and close the manifest.txt file.
§ Navigate to command prompt and type the command
>>cd C:\Users\lenovo\Desktop\java2jar>jar cvfm myjar.jar manifest.txt src\*.class
Explaning
the above command:
myjar.jar
is name of the jar file that you want to create
manifest.txt
is the manifest file that has headers
src\*.class
adds all the .class files available in the src folder.
§
Navigate to command prompt and type
the command
>>cd C:\Users\lenovo\Desktop\java2jar>jar xvf
myjar.jar
§
It creates META-INF folder in
java2jar and it has manifest.MF.
§
Now from the command prompt
type
>>cd C:\Users\lenovo\Desktop\java2jar>java
-jar myjar.jar
It runs the program from the command prompt.
Creating a batch file:
Open a new text document in java2jar folder and
name it as run.bat
Enter java -jar myjar.jar in the file and save
it.
Now double click on run.bat .
The complete folder
java2jar can be shared across any machine.
Labels:
cmd,
command prompt,
jar,
Java,
windows
Wednesday, June 10, 2015
Java program to print two largest numbers
Java program to print maximum of two numbers:
package caveof;
public class Maxtwo {
public void twoMaxNumbers(int[] nums){
int maxone = 0;
int maxtwo = 0;
for(int n:nums){
if(maxone < n){
maxtwo = maxone;
maxone = n;
}
else if(maxtwo < n){
maxtwo = n;
}
}
System.out.println("First Max Number: "+maxone);
System.out.println("Second Max Number: "+maxtwo);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int num[] = {5,34,78,2,45,1,99,23};
Maxtwo twomn = new Maxtwo();
twomn.twoMaxNumbers(num);
}
}
package caveof;
public class Maxtwo {
public void twoMaxNumbers(int[] nums){
int maxone = 0;
int maxtwo = 0;
for(int n:nums){
if(maxone < n){
maxtwo = maxone;
maxone = n;
}
else if(maxtwo < n){
maxtwo = n;
}
}
System.out.println("First Max Number: "+maxone);
System.out.println("Second Max Number: "+maxtwo);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int num[] = {5,34,78,2,45,1,99,23};
Maxtwo twomn = new Maxtwo();
twomn.twoMaxNumbers(num);
}
}
Friday, February 13, 2015
Automation of naukri profile update - Selenium
This script uploads ur profile at naukri.com with out using AutoIt
package Selenium_script;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Upload {
public static String naukari = "https://login.naukri.com/nLogin/Login.php";
public static String nauk = "http://www.naukri.com/";
public static String upload = ".//*[@id='colL']/div[2]/div[1]/a[2]";
public static String view = ".//*[@id='colL']/div[2]/div[1]/span";
public static String view1 = ".//*[@id='colL']/div[2]/div[1]/a[1]";
public static String up_prof = ".//*[@id='uploadLink']";
public static String save = ".//*[@id='editForm']/div[8]/button";
public static String mynauk = ".//*[@id='mainHeader']/div/div/ul[2]/li[2]/a/div[2]";
public static void setClipboardData(String st) {
StringSelection stringSelection = new StringSelection(st);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
public static void main(String[] args) throws AWTException {
WebDriver dri = new FirefoxDriver();
dri.get(nauk);
dri.findElement(By.xpath(".//*[@id='login_Layer']/div")).click();
WebElement fra = dri.findElement(By.xpath(".//*[@id='loginLB']/div[2]"));
fra.click();
dri.findElement(By.id("eLogin")).sendKeys("yourusername"); //Enter your username
dri.findElement(By.id("pLogin")).sendKeys("yourpassword"); // Enter your password
dri.findElement(By.xpath(".//*[@id='lgnFrm']/div[7]/button")).click();
dri.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
dri.manage().window().maximize();
//Logged in
//Clicking on view profile
WebElement view_prof = dri.findElement(By.xpath(view1));
Actions builder = new Actions(dri);
builder.click(view_prof).build().perform();
//Clicking on upload link
WebElement prof_upload = dri.findElement(By.xpath(up_prof));
prof_upload.click();
WebElement attachcv = dri.findElement(By.xpath(".//*[@id='attachCV']"));
Actions builder1 = new Actions(dri);
builder1.click(attachcv).build().perform();
//upload the file
//The below method calls the setclipboard method and put the file path in clipboard
setClipboardData("Path to your resume file");
//The below lines of code will paste the clipboard content and click open button in the modal window
Robot robot = new Robot();
robot.delay(500);
robot.keyPress(KeyEvent.VK_CONTROL); //Press control key
robot.keyPress(KeyEvent.VK_V); //Press key v
robot.keyRelease(KeyEvent.VK_V); // Release "v"
robot.keyRelease(KeyEvent.VK_CONTROL); //Release ctrl key
robot.keyPress(KeyEvent.VK_ENTER); //Press enter key that clicks the open button in the modal
robot.keyRelease(KeyEvent.VK_ENTER); //Release the enter key
robot.delay(1000); //Delay in milli seconds
//Closing the modal window of upload file
WebElement sav_btn = dri.findElement(By.xpath(save));
sav_btn.click();
//Log out button
WebElement my_naukri = dri.findElement(By.xpath(mynauk));
WebElement log_out = dri.findElement(By.xpath(".//*[@id='mainHeader']/div/div/ul[2]/li[2]/div/ul/li[5]/a"));
Actions builder3 = new Actions(dri);
builder3.moveToElement(my_naukri).click(log_out).build().perform();
}
}
package Selenium_script;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Upload {
public static String naukari = "https://login.naukri.com/nLogin/Login.php";
public static String nauk = "http://www.naukri.com/";
public static String upload = ".//*[@id='colL']/div[2]/div[1]/a[2]";
public static String view = ".//*[@id='colL']/div[2]/div[1]/span";
public static String view1 = ".//*[@id='colL']/div[2]/div[1]/a[1]";
public static String up_prof = ".//*[@id='uploadLink']";
public static String save = ".//*[@id='editForm']/div[8]/button";
public static String mynauk = ".//*[@id='mainHeader']/div/div/ul[2]/li[2]/a/div[2]";
public static void setClipboardData(String st) {
StringSelection stringSelection = new StringSelection(st);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
public static void main(String[] args) throws AWTException {
WebDriver dri = new FirefoxDriver();
dri.get(nauk);
dri.findElement(By.xpath(".//*[@id='login_Layer']/div")).click();
WebElement fra = dri.findElement(By.xpath(".//*[@id='loginLB']/div[2]"));
fra.click();
dri.findElement(By.id("eLogin")).sendKeys("yourusername"); //Enter your username
dri.findElement(By.id("pLogin")).sendKeys("yourpassword"); // Enter your password
dri.findElement(By.xpath(".//*[@id='lgnFrm']/div[7]/button")).click();
dri.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
dri.manage().window().maximize();
//Logged in
//Clicking on view profile
WebElement view_prof = dri.findElement(By.xpath(view1));
Actions builder = new Actions(dri);
builder.click(view_prof).build().perform();
//Clicking on upload link
WebElement prof_upload = dri.findElement(By.xpath(up_prof));
prof_upload.click();
WebElement attachcv = dri.findElement(By.xpath(".//*[@id='attachCV']"));
Actions builder1 = new Actions(dri);
builder1.click(attachcv).build().perform();
//upload the file
//The below method calls the setclipboard method and put the file path in clipboard
setClipboardData("Path to your resume file");
//The below lines of code will paste the clipboard content and click open button in the modal window
Robot robot = new Robot();
robot.delay(500);
robot.keyPress(KeyEvent.VK_CONTROL); //Press control key
robot.keyPress(KeyEvent.VK_V); //Press key v
robot.keyRelease(KeyEvent.VK_V); // Release "v"
robot.keyRelease(KeyEvent.VK_CONTROL); //Release ctrl key
robot.keyPress(KeyEvent.VK_ENTER); //Press enter key that clicks the open button in the modal
robot.keyRelease(KeyEvent.VK_ENTER); //Release the enter key
robot.delay(1000); //Delay in milli seconds
//Closing the modal window of upload file
WebElement sav_btn = dri.findElement(By.xpath(save));
sav_btn.click();
//Log out button
WebElement my_naukri = dri.findElement(By.xpath(mynauk));
WebElement log_out = dri.findElement(By.xpath(".//*[@id='mainHeader']/div/div/ul[2]/li[2]/div/ul/li[5]/a"));
Actions builder3 = new Actions(dri);
builder3.moveToElement(my_naukri).click(log_out).build().perform();
}
}
Wednesday, January 14, 2015
Selenium script to get table values
package Ecomm_selenium;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium. WebElement;
import org.openqa.selenium.firefox. FirefoxDriver;
public class Tablevalues {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String site = "http://www.amazon.com/gp/ seller-account/mm-landing. html/ref=footer_seeall?ie= UTF8&ld=AZSOAviewallMakeM";
//String paths = ".//*[@id='fk-mainbody-id']/di v/div[2]";
//String
WebDriver d = new FirefoxDriver();
d.get(site);
//WebElement webtable = d.findElement(By.xpath(".//*[@ id='grey-box']/div"));
int RowIndex = 3;
List<WebElement> Rowcount = d.findElements(By.xpath(".//*[ @id='grey-box']/div/div["+ RowIndex+"]"));
System.out.println("No: of Rows in table:" + Rowcount.size());
//for(WebElement rowelem : Rowcount)
for(int i=0; i <= RowIndex; i++)
{
int ColIndex = 3;
for(int j = 0; j <= ColIndex; j++){
WebElement value = d.findElement(By.xpath(".//*[@ id='grey-box']/div/div["+i+"]/ div["+j+"]/p"));
System.out.println("Row" + i + "Column" + j + "Data" + value.getText());
}
}
d.quit();
}
}
Selenium script to get list of values
//code to get list of values
package Ecomm_selenium;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium. WebElement;
import org.openqa.selenium.firefox. FirefoxDriver;
//Getting list of webElements
public class Login {
/**
* @param args
*/
public static void main(String[] args) {
String paths = ".//*[@id='fk-mainbody-id']/ div/div[2]";
//String
}
}
Subscribe to:
Comments (Atom)