Posts

Showing posts from July, 2018

QA's approach 2 Java - Apache POI

Apache POI - Java API To Access Microsoft Excel Format Files Read Excel file Data package helper; import java.io.IOException; import java.util.Iterator; import java.util.Scanner; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelReadWrite { static XSSFWorkbook book = null; static XSSFSheet sheet = null; XSSFRow row = null; XSSFCell cell = null; // get ExcelReadWrite object using static factory method public static ExcelReadWrite getExcelReaderWriter() { return new ExcelReadWrite(); } // Method to create workbook object to work with Excel static XSSFWorkbook getWorkbook(String filePath) { String path = filePath; try { book = new XSSFWorkbook(path); return book; } catch (IOException e) { // TODO Auto-generated catch block e.p...

QA's approach 2 Java - JDBC API

Java API To Access Relational DB's What is JDBC? JDBC refers to the Java Database Connectivity. It provides java API that allows Java programs to access database management systems (relational database). The JDBC API consists of a set of interfaces and classes which enables java programs to execute SQL statements. Interfaces and classes in JDBC API are written in java. JDBC core components: The JDBC API consists of the following core components: 1.JDBC Drivers 2.Connections 3.Statements 4.ResultSets 1. JDBC Drivers: JDBC driver is a collection of classes which implements interfaces defined in the JDBC API for opening database connections, interacting with database and closing database connections. 2. Connections: Before performing any database operation via JDBC, we have to open a database connection. To open a database connection we can call getConnection() method of DriverManager class. Syntax: Connection connection = DriverManager.getConnection(url, user, p...

QA's approach 2 Java - Logging API - Log4j

Log4j Log4j is a Framework(API) written in Java & distributed under Apache Software license, used for debugging. Log4j has 3 main components: 1. loggers: To capture the logging information 2. appenders: To publish the logging information to various destinations. An output destination is called an appender. 3. layouts: To format logging information in different styles. There are three ways to configure log4j: 1. Using properties file. 2. Using Java code programatically. 3. Using XML file. Configuring Log4j using properties files & programmatically Configuring log4j involves the following tasks: 1. Configuring the root logger 2. Configuring individual logger 3. Specifying appenders 4. Specifying message layout Configure the root logger The root logger is the base logger from which other loggers inherits. Syntax for configuring the root logger is as follows: log4j.rootLogger=level[, appender1, appender2…] Where level can be one of the f...

QA's approach 2 Java - Comparable & Comparator Interfaces

Comparable Interface Available in java.lang package, hence by default available to all the classes. abtract method: public int compareTo(Object arg0) Used for Natural sorting order - Ascending order Can be overridden to be utilized for sorting based on our requirement for our class object. Comparator Interface Available in java.Utilpackage abtract method: public int compare(Object arg0, Object arg1) Used for Customized sorting order  Need to implement the logic for this abstract method according our requirement for achieving the required sorting order. How to sort elements of arrays and Wrapper classes? Lists and arrays of objects implement Comparable interface, hence can be sorted automatically by Collections.sort (and Arrays.sort). We can sort elements of arrays and Wrapper classes, since they already implements Comparable. Example: import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; p...

QA's approach 2 JAVA - Collection Framework cont.. - Cursor Objects

Problems with Enumeration Enumeration interface is used to iterate over legacy classes like Vector. It doesn't have the methods to add, remove, transverse in reverse direction, etc. Methods available in Enumeration interface: public boolean hasMoreElements() public Object nextElement() Iterator vs ListIterator 1) Iterator is used for traversing List and Set both. We can use ListIterator to traverse List only, we cannot traverse Set using ListIterator. 2) We can traverse in only forward direction using Iterator. Using ListIterator, we can traverse a List in both the directions (forward and Backward). 3) We cannot obtain indexes while using Iterator We can obtain indexes at any point of time while traversing a list using ListIterator. The methods nextIndex() and previousIndex() are used for this purpose. 4) We cannot add element to collection while traversing it using Iterator, it throws ConcurrentModificationException when you try to do it. We can add e...

QA's approach 2 Java - Collections Framework Hierarchy & Important methods available

Image
Practical way to identify the Hierarchy & What were available methods under them Assume we wanted to know Hierarchy of ArrayList & the Methods available in it. Step 1: Create a class extending ArrayList class as follows in Eclispe package collectionExamples; import java.util.ArrayList; public class InheritAbstractList extends ArrayList<Object>{ public static void main(String[] args) { } } //Right click ->Source->Override/Implement methods ->Will display a window to select methods to override/implement } Then our class file will now include all the methods available in ArrayList Class as follows package collectionExamples; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Spliterator; import java.util.function.Consumer; import java.util.funct...

QA's approach 2 Java - Exception Handling with examples

Exception Handling: Exceptions arise from different kind of situations such as: 1. Invalid data entered by user & its not validated & allowed 2. Insufficient RAM/Disk space 3. Hardware failure 4. Network connection failure 5. Database server down etc.  Java being an object oriented programming language, whenever an error occurs while executing a statement, it creates an exception object and then the normal flow of the program halts and JVM tries to find the Handler that can handle the raised exception.  The exception object contains a lot of debugging information such as method hierarchy, line number where the exception occurred, type of exception etc.  When the exception occurs in a method, the process of creating the exception object and handing it over to runtime environment is called “throwing the exception”. Once runtime receives the exception object, it tries to find the handler for the exception. Exception Handler is the block of ...

QA's approach 2 Java - Regular Expressions

Image
Regular Expressions: abc…    Letters 123…    Digits Literal escape \x \d           Any Digit \D          Any Non-digit character .             Any Character \.            Period Grouping       [...] Union          [a-e][i-u] Intersection   [a-z&&[aeiou]] Union             [a-e][i-u] [abc]      Only a, b, or c [^abc]    Not a, b, nor c Range          a-z [a-z]      Characters a to z [0-9]      Numbers 0 to 9 \w          Any Alphanumeric character \W         Any Non-alphanumeric character {m}       m Repetitions {m,n}    m to n Repetitions *      ...

QA's approach 2 Java - Scanner Class Examples

Image
Scanner Class examples How does a Scanner work? Basically, a Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace ( blanks, tabs, and line terminators ). The parsed tokens can be converted into primitive types and Strings using various next methods. Here’s the simplest example of using a Scanner to read an integer number from the user: Delimiter Delimiter will be used by scanner object to tokenize string. This is helpful if we are using Scanner to split String into multiple tokens usedelimiter(String pattern) method sets the delimiter of this Scanner object This method is necessary specially in dealing with files as a data source Important Methods in Scanner class: next() - to iterate to the next token hasNext() - return true if next token exists hasNext(String p) - return true if next token exists  Example - Reading User input from Keyboard package fileHandling; import java.util.Scanner; public class...

QA's approach 2 Java - File Creation with Date and Time

File Creation in java Example package fileHandling; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class CreateFile { /** * @param args * @throws ClassNotFoundException */ public static void main(String... args) throws ClassNotFoundException { String fileName = null; Scanner sc = new Scanner(System.in); System.out.println("Please enter the file name to create"); fileName = sc.next(); String filePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "fileHandling" + File.separator + fileName + "_" + GetCurrentTimeStamp().replace(":", "_").replace(".", "_") + ".txt"; // System.out.println(filePath); File createNew = null; try { createNew = new File(filePath); // returns true if new file is created else is fi...