Supporting Java APIs for Selenium
Created by Kavan Sheth
Best viewed in Chrome, Firefox, Opera or A browser supporting HTML5.
Use arrow keys ( up ↑, down ↓, left ←, right ↑) to navigate. Uses Reveal.js by Hakim El Hattab
Press ESC to enter the slide overview.
public static String runCommand(String Command, String envHost, String envUser, String envPass )
{
String output = null;
int exitStatus = 0;
try{
JSch jsch=new JSch();
//To avoid Strict key checking(Explained on next page)
JSch.setConfig("StrictHostKeyChecking", "no");
//create a session
Session session=jsch.getSession(envUser, envHost, 22);
//set password
session.setPassword(envPass);
//few configurations
session.setConfig("PreferredAuthentications",
"publickey,keyboard-interactive,password");
//connect to your session
session.connect();
String command=Command;
//Open channel to execute command and get input stream for output
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
//while channel is open, read output data from input stream
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
output = new String(tmp, 0, i);
}
if(channel.isClosed()){
if(in.available()>0) continue;
exitStatus= channel.getExitStatus();
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
if (exitStatus == 0)
return output.replaceAll("[\\n\\r]", "");
else
return "";
}
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.activation.*;
import javax.mail.Transport;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
public class MailClient extends Authenticator{
/**
* @author : Eran Chinthaka
* @date : Apr 13, 2008
*/
// Edit these settings with your username and password
private String gmailUserName = "gmailuser@gmail.com";
private String gmailPassword = "password";
//=====================================================
public void postMail(String recipients[], String subject,
String message, String from) throws MessagingException {
boolean debug = false;
//Set the host smtp address
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
Session session = Session.getDefaultInstance(props, this);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo =
new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
//set text here
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(message);
// Set the email attachment file
MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource("fileName") {
@Override
public String getContentType() {
return "application/octet-stream";
}
};
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
attachmentPart.setFileName("fileName");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messagePart);
multipart.addBodyPart(attachmentPart);
msg.setContent(multipart);
Transport.send(msg);
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(gmailUserName, gmailPassword);
}
public static String getDateTime()
{
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
return dateFormat.format(date);
}
public static void main(String[] args)
{
MailClient myMail = new MailClient();
String[] recipients={"receipient1@gmail.com","receipient2@gmail.com"};
try{
myMail.postMail(recipients,"Status "+ getDateTime(), "msg line 1\n msg line 2\n msg line 3\n ", "sender@gmail.com");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
if (conn == null)
{
String url ="jdbc:oracle:thin:@" + dbHost + ":1521:" + dbSID;
try{
conn = DriverManager.getConnection(url, dbUsername, dbPass);
}
catch(Exception e){
e.printStackTrace();
}
}
try {
if (connection == null) {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\database1.accdb";
connection = DriverManager.getConnection(database, "", "");
}
} catch (Exception ex) {
}
Connection connection;
try {
Class.forName("com.mysql.jdbc.Driver");
String database = "jdbc:mysql://localhost/test";
connection = DriverManager.getConnection(database, "root", "abc");
}
catch(Exception e)
{
e.printStackTrace();
}
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString(3);
String last = rs.getString("last");
}
try{
FileInputStream fstream = new FileInputStream( new java.io.File(".").getCanonicalPath() +"\\data.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
System.out.println(strLine);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Here we created BufferedReader from Streams, which can also be created from readers as following:
FileReader fstream = new FileReader( new java.io.File(".").getCanonicalPath() +"\\data.txt");
BufferedReader br = new BufferedReader(fstream);
Best way to work with streams/reader is to first identify function you are interested in, like here we are interested in readLine(), then look at constructor of that stream/reader and supply required stream or reader.
// Format a string containing a date.
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;
Calendar c = new GregorianCalendar(1995, MAY, 23);
String s = String.format("Duke's Birthday: %1$tb %1$te, %1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"
StringBuilder sb = new StringBuilder();
// Send all output to the Appendable object sb
Formatter formatter = new Formatter(sb, Locale.US);
// Explicit argument indices may be used to re-order output.
formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")
// -> " d c b a"
// Optional locale as the first argument can be used to get
// locale-specific formatting of numbers. The precision and width can be
// given to round and align the value.
formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E);
// -> "e = +2,7183"
try{
FileWriter writer1 = new FileWriter(new java.io.File(".").getCanonicalPath() +"\\data.txt", false);
BufferedWriter o1 = new BufferedWriter(writer1);
for (String data: stringArray )
{ o1.write( "my " + data);
o1.newLine();
}
o1.close();
}
catch(Exception e)
{
e.printStackTrace();
}
OR
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
while (String data: stringArray) {
outputStream.println(data);
}
outputStream.close();
}
public static void writeToExcelHSSF(String filename, PrintWriter logger)
{
try{
//Create a workbook, as here we are trying to modify an Existing file need to provide FileInputStream as argument
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(path + xlsFile));
//FileOutputStream will be needed while writing changes back to a xls file
FileOutputStream stream = new FileOutputStream(path + "final1.xls");
//Get sheet by providing index of the sheet
HSSFSheet sheet = wb.getSheetAt(0);
//Creating a evaluator, it will be used to evaluate formula of a cell
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb);
//Get numder of rows of a sheet
int rows = sheet.getPhysicalNumberOfRows();
System.out.println("Sheet " + wb.getNumberOfSheets() + " \"" + wb.getSheetName(0) + "\" has " + rows + " row(s).");
//Create a row object;
HSSFRow row;
//Different cell objects
HSSFCell scriptCell;
HSSFCell priceCell;
HSSFCell valuationCell;
HSSFCell profitCell;
String scriptName;
for(int k=1;k< rows;k++){
//get row based on index(row number)
row = sheet.getRow(k);
//get particular cell of a row
scriptCell = row.getCell(9);
//get string value from the cell
scriptName =scriptCell.getStringCellValue();
priceCell =row.getCell(5);
valuationCell =row.getCell(6);
profitCell =row.getCell(7);
//set value in a cell, (here parseStocks is just a user defined function to fetch value of a stock)
priceCell.setCellValue(parseStocks(path + filename,scriptName));
//Trigger cache clearance, so evaluation of formula on this cell is done with latest value
evaluator.notifyUpdateCell(priceCell);
//Re-evaluate formula of a cell
evaluator.evaluateFormulaCell(valuationCell);
evaluator.evaluateFormulaCell(profitCell);
}
//writing back workbook to output stream
wb.write(stream);
stream.close();
}
catch( IOException e)
{
e.printStackTrace(logger);
}
}
Following are few points by rgettman at here
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<RollingFile name="Rolling-default" fileName="logs/bssauto.log"
filePattern="logs/$${date:yyyy-MM}/bssauto-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout pattern="%d %t %-5p %c{2} - %m%n"/>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
</RollingFile>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</Console>
<File name="FileLogger" fileName="logs/bssauto.log" append="false">
<PatternLayout pattern="%d %t %-5p %c{2} - %m%n"/>
</File>
</Appenders>
<Loggers>
<Root level="trace">
<AppenderRef ref="Rolling-default"/>
</Root>
</Loggers>
</Configuration>
Log outputs so you can have idea about patterns used
Log output for RollingFile and File appender
2014-08-04 18:22:44,127 main TRACE tests.PayGoTests - entry params(100018)
2014-08-04 18:22:44,135 main INFO tests.PayGoTests - Running create BAN with PricePlan flow : PP 100018
2014-08-04 18:22:44,139 main TRACE tests.PayGoTests - entry params(http://optimus-z2:9260, ChromeDriver: chrome on WIN8 (265acb7076f7ee33e9dcf46742ea6610), rkadm, rkadm)
2014-08-04 18:22:46,184 main INFO tests.PayGoTests - Not already logged in. need to login.
2014-08-04 18:22:47,834 main TRACE tests.PayGoTests - exit with(com.redknee.bssauto.pages.HomePage@121b9a0)
2014-08-04 18:22:47,836 main TRACE tests.PayGoTests - entry params(com.redknee.bssauto.pages.HomePage@121b9a0, 97035, GSM, 1)
Log output for STDOUT
2014-10-13 01:17:09,901 TRACE [main] tests.PayGoTests (PayGoTests.java:285) - entry params(100018)
2014-10-13 01:17:09,917 INFO [main] tests.PayGoTests (PayGoTests.java:286) - Running create BAN with PricePlan flow : PP 100018
2014-10-13 01:17:09,918 TRACE [main] flow.PayGoFlows (PayGoFlows.java:79) - entry params(http://hibbert:9260, ChromeDriver: chrome on WIN8 (035fac047d681e18221ea8489aba5310), rkadm, rkadm)
2014-10-13 01:17:22,070 INFO [main] flow.PayGoFlows (PayGoFlows.java:93) - Not already logged in. need to login.
2014-10-13 01:17:28,822 TRACE [main] flow.PayGoFlows (PayGoFlows.java:97) - exit with(com.redknee.bssauto.pages.HomePage@ae525c)
2014-10-13 01:17:28,823 TRACE [main] flow.PayGoFlows (PayGoFlows.java:111) - entry params(com.redknee.bssauto.pages.HomePage@ae525c, 55692, GSM, 1)
private static Logger logger= LogManager.getLogger("myLogger");
catch(NoSuchElementException e)
{
logger.error("Seems Page is not Loaded. stack trace :" + e);
logger.catching(e);
logger.info("Catching Exception")
return logger.exit(null);
}
lower number - high priority, higher number - low priority
<PatternLayout pattern="%d %t %-5p %c{2} - %m%n"/>you need to provide HTMLLayout as following
<HTMLLayout charset="UTF-8" title="log"></HTMLLayout>
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
loggerConfig.setLevel(level);
ctx.updateLoggers(); // This causes all Loggers to refetch information from their LoggerConfig.