If you found following error while connecting a secure server
"org.apache.axis2.AxisFault: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"
follow the below step to resolve the issue.
Step 1. Go to your Mozilla Firefox and browse the server URL and follow the highlighted steps.
Step 2. Download the certificate by following highlighted steps and save it to location direction with file extension ".crt", e.g: example.crt.
Step 3. Now open command prompt with "run as administrator" and run the following command
Selenium is one of the best tool for automating web application testing. If number of pages of web application increase gradually, it is really hard for application tester to test every page after new deployment.
Selenium provide web driver for almost browser including firefox, IE, Google Chrome etc. Even you can integrate selenium web driver with Junit, TestNG or plan Java, .Net code.
Selenium provide two type of web drivers. Browser base driver like FirefoxDriver will open the Firefox browser and perform the test. In this case, Selenium will fill up all fields and click on necessary places, just like an automated robot. But if you want to write test cases that does't require browser then you can use HtmlUnitDriver. It will create instance of in-memory browser. But browser base driver is important when you want to test your application whether its compatible with all modern browser like Google chrome, Firefox and IE.
Following snippet is showing initialization of Firefox web driver and HtmlUnitDriver.
Create a new instance of the html unit driver
private WebDriver driver= new HtmlUnitDriver();
// Create a new instance of the Firefox driver
private WebDriver driver= new FirefoxDriver();
Here is an example showing how to perform login before test any secure page. In Junit @BeforeClass annotation method will be called before run any test case.
@BeforeClass
public static void setUpBeforeClass() throws Exception {
entity = new Users("moin", "123", "abc@gmail.com", "xyz",
"");
// Create a new instance of the html unit driver
driver = new HtmlUnitDriver();
// And now use this to visit your login URL. e.g
driver.get(serverBaseUrl + "/login");
// set the user name in user id text field
driver.findElement(By.name("j_username"))
.sendKeys(entity.getUserName());
// set the password in user password text field
driver.findElement(By.name("j_password"))
.sendKeys(entity.getPassword());
driver.findElement(By.className("pull-right")).click();
System.out.println(driver.getPageSource());
if (driver.findElement(By.cssSelector(".jumbotron")).getText()
.contains("Welcome to ScrapperX")) {
System.out.println("Login Success");
} else {
System.out.println("Login fail");
throw new Exception("Login Require");
}
Thread.sleep(1000);
}
After login you can test any secure page in the same session. Below snippet is showing how to test "update user profile page"
@Test
public void testUpdateProfile() {
driver.get(serverBaseUrl + "/users/editprofile");
// clear the exist first name or else sendKeys will append new text
driver.findElement(By.name("firstName")).clear();
driver.findElement(By.name("firstName"))
.sendKeys(entity.getFirstName());
driver.findElement(By.name("lastName")).clear();
driver.findElement(By.name("lastName")).sendKeys(entity.getLastName());
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys(entity.getPassword());
driver.findElement(By.name("c_password")).clear();
driver.findElement(By.name("c_password"))
.sendKeys(entity.getPassword());
// in several way you can select a checkbox
/*
* List checkbox =
* driver.findElements(By.name("paymentActive")); ((WebElement)
* checkbox.get(0)).click();
*/
// select paymentActive checkbox
WebElement checkbox = driver.findElement(By.name("paymentActive"));
if (checkbox.isSelected() == false) {
checkbox.click();
}
driver.findElement(By.className("btn")).click();
System.out.println(driver.findElement(By.cssSelector(".alert"))
.getText());
assertTrue("Update user profile fail",
driver.findElement(By.cssSelector(".alert")).getText()
.contains("Update Complete"));
}
You can access any field or html element by css class name, id and field name.
Following example is showing how to select a drop-down option.
Select cardTypeDropDown = new Select(driver.findElement(By
.name("cardType")));
cardTypeDropDown.selectByValue("visa");
Here is an working example of testing Google search.
package com.scrapperx.web.controller;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class GoogleSearchTest {
@Test
public void testGoogleSearch() throws InterruptedException {
// Create a new instance of the html unit driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
System.out.println("http://www.google.com");
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("tometo");
// Now submit the form. WebDriver will find the form for us from the
// element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
Thread.sleep(10000);
driver.quit();
}
}
Spring bean instance will be created depend on scope specified on that bean , spring container support five types of scope
singleton – Return a single bean instance per Spring IoC container
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request.
session – Return a single bean instance per HTTP session.
globalSession – Return a single bean instance per global HTTP session.
Spring container default scope is singleton , so you have to be careful before use bean instance . In multi-thread environment , singleton instance must be thread safe to avoid race condition . In that situation you might use prototype scope. Other three scopes are only valid in the context of a web-aware Spring ApplicationContext.
Example
Here is an example to explain difference between singleton and prototype .
1. Singleton Example: Since no bean scope is specified ,default to singleton
package com.example.springscope;
import org.springframework.stereotype.Service;
@Service("userService")
// default scope is Singleton
public class User {
private Integer id;
private String userName;
public int getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String toString(){
return "[ ID : "+id+" Name :"+userName+"]";
}
}
Configuration XML : component-scan will allow us to use annotation base bean declaration and enable auto component scan. All beans declared in com.example and its child package will be available in spring context.
Test example :
package com.example.springscope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "app-config.xml" });
// retrieve configured instance
User customerA = (User) context.getBean("userService");
customerA.setId(1);
customerA.setUserName("Jeff");
System.out.println(" Customer Info A:" +customerA);
// Since Scope is singleton , same instance will be return to caller
User customerB = (User) context.getBean("userService");
System.out.println(" Customer Info B:" +customerB);
}
}
Output :
Customer Info A:[ ID : 1 Name :Jeff]
Customer Info B:[ ID : 1 Name :Jeff]
In this example Id and name has been set on the customerA but same value is also showing on customerB , because of singleton scope. Spring container will create only one object for singleton scope , that will be return to caller every time.
Prototype Example
If you want new instance every time , you have to use prototype scope .
package com.example.springscope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service("userService")
@Scope("prototype")
public class User {
private Integer id;
private String userName;
public int getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String toString(){
return "[ ID : "+id+" Name :"+userName+"]";
}
}
Test Example :
package com.example.springscope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "app-config.xml" });
// retrieve configured instance
User customerA = (User) context.getBean("userService");
customerA.setId(1);
customerA.setUserName("Jeff");
System.out.println(" Customer Info A:" +customerA);
// Since Scope is prototype , new instance will be return to caller
User customerB = (User) context.getBean("userService");
System.out.println(" Customer Info B:" +customerB); // all fields value will be null
customerB.setId(2);
customerB.setUserName("Jhon");
System.out.println(" Customer Info B:" +customerB);
}
}
Output :
Customer Info A:[ ID : 1 Name :Jeff]
Customer Info B:[ ID : null Name :null]
Customer Info B:[ ID : 2 Name :Jhon]
You can download this example project from github
https://github.com/sujanctg2005/Example
File Modification, Copy, delete and create new file is quite easy in java programming. Here I wrote some java file operation utility method that might be useful for your application. Java File Copy Method
public static void copyfile(String srFile, String dtFile) throws Exception {
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
// For Append the file.
// OutputStream out = new FileOutputStream(f2,true);
// For Overwrite the file.
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
Java Delete File Method
public static void removeFile(String fileName) throws Exception {
File file = new File(fileName);
if (file.exists()) {
boolean success = file.delete();
if (!success) {
throw new Exception("Fail to delete existing file");
}
}
}
Java Rename File Method
public static void renameFile(String oldName, String newName) throws IOException {
File srcFile = new File(oldName);
boolean bSucceeded = false;
try {
File destFile = new File(newName);
if (destFile.exists()) {
if (!destFile.delete()) {
throw new IOException(oldName + " was not successfully renamed to " + newName);
}
}
if (!srcFile.renameTo(destFile)) {
throw new IOException(oldName + " was not successfully renamed to " + newName);
} else {
bSucceeded = true;
}
} finally {
if (bSucceeded) {
srcFile.delete();
}
}
}
Java List of files in specified directory with filter option
List fileList = FileUtil.dirlist(sourceLocation, "*.csv");
public static List dirlist(String path, String filter) throws FileNotFoundException {
File dir = new File(path);
FileFilter fileFilter = new WildcardFilter(filter);
File[] chld = dir.listFiles(fileFilter);
List fileList = new ArrayList();
if (chld == null) {
log.error("Specified directory does not exist or is not a directory.");
throw new FileNotFoundException("Specified directory does not exist or is not a directory.");
} else {
for (int i = 0; i < chld.length; i++) {
File file = chld[i];
if(file.isFile()) {
fileList.add(file);
}
}
}
return fileList;
}
Java List of files in specified directory
public static List dirlist(String path) throws FileNotFoundException {
File dir = new File(path);
File[] chld = dir.listFiles();
List fileList = new ArrayList();
if (chld == null) {
log.error("Specified directory does not exist or is not a directory.");
throw new FileNotFoundException("Specified directory does not exist or is not a directory.");
} else {
for (int i = 0; i < chld.length; i++) {
File file = chld[i];
if(file.isFile()) {
fileList.add(file);
}
}
}
return fileList;
}
Eclipse is an industry leader in IDE market, it is used very extensively in developing projects all around the world. Similarly, Maven is a high-level, intelligent project management, build and deployment tool provided by Apache’s software foundation group. Maven deals with application development lifecycle management.
Maven–Eclipse Integration makes the development, testing, packaging and deployment process easy and fast. Maven Integration for Eclipse provides a tight integration for Maven into the IDE and avails the following
features:
· It helps to launch Maven builds from within EclipseIt avails the dependency management for Eclipse build path based on Maven's pom.xml
· It resolves Maven dependencies from the Eclipse workspace without installing to local Maven repository
· It avails an automatic downloading of the required dependencies from the remote Maven repositories
· It provides wizards for creating new Maven projects, pom.xml or to enable Maven support on plain Java project
· It helps to search quickly for dependencies in Maven remote repositories
· It quickly fixes in the Java editor for looking up required dependencies/jars by the class or package name.
What do you Need?
1. Get the Eclipse Development Environment :
In this tutorial we are using the SpringSource Tool Suite .This tool based on eclipse and maven is integrate with this , so no need to download or configure maven with eclipse , which can be downloaded from http://www.springsource.com/products/springsource-tool-suite-download
Download and Install Eclipse
First download and install the SpringSource Tool Suite on your development machine .
Steps to create maven web project
1.Open eclipse IDE and
go to File->New-> Other..
as shown in Figure 1 below:
1. Select maven ->maven project
as shown in Figure 2 below:
Click next->next-> in Filter field type 'webapp'
and select group id org.apache.maven.archetypes
as shown in Figure 3 below:
Click next-> give group id name 'com.testmaven' and artifact ' hello' ,other option remain default
as shown in Figure 4 below:
Click finish . Select Project hello and run on server
select springsource dm server and click finish (you can add any server such as tomcat by manually define a new server)
Now you can see Hello World out put in the browser