Demystifying Micro Services Architecture

What is Micro Services?

Micro Services Architecture (MSA) is an implementation of Service Oriented Architecture (SOA). Micro Services allows you to create an API for every functionality. Client Applications can orchestrate these micro services to provide a meaningful application.

Micro services also allow you to extend your applications on multiple consumer platforms, such as your Mobile device and Desktop applications.

 

e.g., If you are going to build a Candidate Tracking System, in place of building everything as a monolithic web application, you can expose various parts of candidate using various microservices.

 

Let’s say in the this application, you would like to create candidate information, update candidate information, read candidate information and deactivate his profile. In the micro services architecture, you will create 4 web services to reflect this:

 

  1. Create candidate information,
  2. Update candidate information,
  3. Read candidate information and
  4. Deactivate his profile

 

The above micro services will ensure that you can create a functional application that can consume data from multiple sources – your mobile applications as well as desktop web applications. This also will save you from the peril of rewriting and maintaining the same code at multiple places.

 

I will add a working example of microservices in the next blog. let me know in the comments how you feel about microservices and what are your favorite microservices frameworks.

 

Advertisements
Posted in Uncategorized | Leave a comment

Hybrid Framework using Selenium – Step by Step Guide

Hybrid Framework in Testing means a combination of few testing frameworks and approaches, namely:big-logo1

  1. Data Driver/Keyword Driven Framework – This Framework allows you to read test data from an external system, such as a Data base or a File system. In place of hardcoding the test data, you use external data.
  2. Module Based Testing Framework/Page Object Model Framework – This framework allows you to extract common functionalities. In Page Object Model, you treat a page like a class and functionality provided by it as a function. e.g., a registration page can be created as a RegistrationPageObject class and register(User user) can be used as a common method anyone  can use to register a user.

Here is how you implement:

  1. Create a database and add your test data. We will read test data from this table. Open mySQL Workbench and connect to your local mysql server (You can download mysql server from mysql website)

CREATE SCHEMA `hybridtest` ;

CREATE TABLE `hybridtest`.`registration_data` (
`id` INT NOT NULL AUTO_INCREMENT,
`firstname` VARCHAR(45) NULL,
`lastname` VARCHAR(45) NULL,
`username` VARCHAR(45) NULL,
`password` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `username_UNIQUE` (`username` ASC));

2. Insert 2 rows

id, firstname, lastname, username, password, expected
‘1’,’mark’,’ouren’,’mark_u’,’pass’,’1′
‘2’,’john’,’smith’,”,’pass’,’0′

If you notice for the second row, there is no username. This is to test a negative scenario –  If a user does not enter a username, you do not expect him to register.

3. Create Page Object to represent Registration Page.

package com.training.examples.hybrid.pageobject;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

import com.training.examples.hybrid.model.User;

public class RegisterPage {

	public boolean register(WebDriver driver, User user) {

		boolean status = false;
		// Locate elements and populate relevant fields
		//

		driver.get("http://newtours.demoaut.com/" + "/mercurysignon.php");

		driver.findElement(By.linkText("CONTACT")).click();

		driver.findElement(By.linkText("REGISTER")).click();

		// Go to DB and read these rows and

		driver.findElement(By.name("userName")).clear();
		driver.findElement(By.name("userName")).sendKeys("john.doe");
		driver.findElement(By.name("password")).clear();
		driver.findElement(By.name("password")).sendKeys("john");
		driver.findElement(By.name("firstName")).clear();
		driver.findElement(By.name("firstName")).sendKeys("sansa2016");
		driver.findElement(By.name("lastName")).clear();
		driver.findElement(By.name("lastName")).sendKeys("sansaln");
		driver.findElement(By.name("phone")).clear();
		driver.findElement(By.name("phone")).sendKeys("123456789");
		driver.findElement(By.id("userName")).clear();
		driver.findElement(By.id("userName")).sendKeys("sansa@sansa.com");
		driver.findElement(By.id("email")).clear();
		driver.findElement(By.id("email")).sendKeys("sansa2016");
		driver.findElement(By.name("password")).clear();
		driver.findElement(By.name("password")).sendKeys("sansa2016");
		driver.findElement(By.name("confirmPassword")).clear();
		driver.findElement(By.name("confirmPassword")).sendKeys("sansa2016");
		driver.findElement(By.name("register")).click();
		// driver.findElement(By.linkText("SIGN-OFF")).click();

		// Verify registration was successful by checking is string "Thank you for
		// registering." is found
		String registrationSuccesfulMessage = "Thank you for registering.";
		status = driver.getPageSource().contains(registrationSuccesfulMessage);
		
		return status;
	}
}

4. Create a User class

package com.training.examples.hybrid.model;

public class User {
	public String firstname;
	public String lastname;
	public String phone;
	public String email;
	public String username;
	public String password;
	public int expected;
	
}

4. Create a UserDAO class. This class will read test data from the database. Make sure that mysql connect for Java is in your classpath.

package com.training.examples.hybrid.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.training.examples.hybrid.model.User;

public class UserDAO {
	
	public List getTestUsersData() throws Exception {
		List  users = new ArrayList ();
		Statement stmt = null;
		Connection con = null;
		// 1. Load a mysql driver
		Class.forName("com.mysql.jdbc.Driver").newInstance();

		// 2. Create a Connection
		String url = "jdbc:mysql://localhost:3306/hybridtest?" + "user=root&password=password";
		con = DriverManager.getConnection(url);

		// 3. Create a Statement
		stmt = con.createStatement();
		// "sure"
		// System.out.println("\"" + message + "\"");
		// 4. Execute Statement
		String query = "select * from hybridtest.registration_data";
		System.out.println("query = " + query);

		ResultSet rs = stmt.executeQuery(query);
		while (rs.next()) {
			int id = rs.getInt("id");
			String firstname = rs.getString("firstname");
			String lastname = rs.getString("lastname");
			String username = rs.getString("username");
			String password = rs.getString("password");
			int expected = rs.getInt("expected");
			
			User u = new User();
			u.firstname = firstname;
			u.lastname = lastname;
			u.username = username;
			u.password = password;
			u.expected = expected;
			

			System.out.println(id + " - " + firstname + " - " + lastname + " - " + username + " - " + password + " - " + expected);
			users.add(u);
		}
		//
		return users;

	}
}

4. Create a Test class that would run the test case. This will first read data from the database and then pas it to the register method. (Make sure to download gecko or firefox driver and point to it in the code below )

package com.training.examples.hybrid;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.training.examples.hybrid.dao.UserDAO;
import com.training.examples.hybrid.model.User;
import com.training.examples.hybrid.pageobject.RegisterPage;

public class SeleniumMercuryDemo {

	private WebDriver driver;
	private String baseUrl;
	private boolean acceptNextAlert = true;
	private StringBuffer verificationErrors = new StringBuffer();
	List users = new ArrayList();

	@Before
	public void setUp() throws Exception {
		// For Windows FF
		// System.setProperty("webdriver.gecko.driver",
		// "C:\\Softwares\\geckodriver-v0.11.1-win64\\geckodriver.exe");

		// For Mac FF
		System.setProperty("webdriver.gecko.driver", "/Users/amitesh.sinha/Softwares/geckodriver");
		driver = new FirefoxDriver();

		users = new UserDAO().getTestUsersData();

		baseUrl = "http://newtours.demoaut.com/";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		driver.manage().window().fullscreen();
	}

	@Test
	public void testPositiveScenario() throws Exception {
		User user = new User();
		user = users.get(0);

		// As the data is "Good" data, we expect this test to pass
		// id, firstname, lastname, username, password, expected
		// '1','mark','ouren','mark_u','pass','1'

		boolean expected = new RegisterPage().register(driver, user);
		assertTrue("Test Failed as User SHOULD BE able to register", expected);

	}

	@Test
	public void testNegativeScenario() throws Exception {
		User user = new User();
		user = users.get(1);

		// As the data is "Bad" data - it's missing username, we expect this test to
		// fail
		// id, firstname, lastname, username, password, expected
		// '2','john','smith','','pass','0'

		boolean expected = new RegisterPage().register(driver, user);
		assertFalse("Test Failed as User SHOULD NOT BE able to register", expected);

	}

	@After
	public void tearDown() {
		driver.close();
	}

}

Now you should be all good with Hybrid Framework.

To become efficient with Hybrid Framework, you should practice and build another example. Would love to hear from you what else did you implement – share that in the comments section below.

 

 

 

 

Posted in Uncategorized | Tagged , , | Leave a comment

How to fix Appium UiAutomatorviewer issue?

Recently one of my students was getting this error – I thought I would put it here in case anyone else could be benefited:

Issue:

On clicking uiautomatorviewerbat file, i am getting this error in cmd

-Djava.ext.dirs=..\lib\x86_64;..\lib is not supported. Use -classpath instead.
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Press any key to continue . . .

Solution:

This issue is caused by incompatible Java version. If you are getting this issue, please uninstall JDK 9 and install JDK 8. This will fix your issue.

 

 

Posted in Uncategorized | Leave a comment

Download the SourceTree app from https://www.sourcetreeapp.com/ for this tutorial to work.

1)   Setting up for the first time

Add username/password by clicking on settings (gear) > Accounts icon

Picture1

 

Click on Add button. Click on Connect button

Picture2

 

Login to bitbucket

Picture3

 

Follow the steps and your username/password will be saved.

 

2)   First Time Checking out (aka Cloning)

Go to SourceTree Application

Picture5

Follow the Clone Wizard

Picture6

Picture7

Once successful, you will see the repo in the list below.

Picture8

 

 

 

3)   Import in Eclipse and Run on Server

Instructions have been posted before on this. If you can not locate this, add a comment below.

4)   Checking in (aka Commit and Push)

Change a file

Go to SourceTree Application

Picture9

 

Commit

Picture10

Push

Picture11

Picture12

You are all set. You can verify your changes on bitbucket website

 

 

 

 

Posted in Uncategorized | Leave a comment

One to many relationship example using Hibernate – Step by Step Instruction

One to many relationship example using Hibernate

One to many relationship using Hibernate can be super useful for any practical purposes. Here are step by step instructions on how to do the same:
In this example There is a one to many relationship between User and User Purchase.
1. Create User Table

	CREATE DATABASE IF NOT EXISTS training; 
	CREATE TABLE IF NOT EXISTS
	training.User ( id INT NOT NULL AUTO_INCREMENT , 
	username VARCHAR(250) NOT NULL , 
	password VARCHAR(250) NOT NULL , 
	email_address VARCHAR(250) NULL ,
	PRIMARY KEY (id) , UNIQUE INDEX
	username_UNIQUE (username ASC) );

2. Create User Purchase Table

	CREATE TABLE `training`.`user_purchase` (
		  `iduser_purchase` INT NOT NULL,
		  `user_id` INT NULL,
		  `item` VARCHAR(45) NULL,
		  `price` FLOAT NULL,
		  PRIMARY KEY (`iduser_purchase`),
		  INDEX `user_id_idx` (`user_id` ASC),
		  CONSTRAINT `user_id`
		    FOREIGN KEY (`user_id`)
		    REFERENCES `training`.`User` (`id`)
		    ON DELETE CASCADE
		    ON UPDATE CASCADE);

3. Create UserPurchase Class

package com.st.model;


public class UserPurchase {
	private Integer purchaseId;
	private User user;
	private float price;
	private String item;

	public Integer getPurchaseId() {
		return purchaseId;
	}

	public void setPurchaseId(Integer purchaseId) {
		this.purchaseId = purchaseId;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}

	public String getItem() {
		return item;
	}

	public void setItem(String item) {
		this.item = item;
	}
}

4. Create User Class

package com.st.model;

import java.util.HashSet;
import java.util.Set;

/**
@author asinha
 *
 */
public class User {
	private int id;

	private String emailAddress;
	private String username;
	private String password;
	
	//Create a new variable to indicate collection of UserPurchase
	//This shows one to many relationship between User and UserPurchase
	private Set userPurchases = new HashSet();
	
	

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getEmailAddress() {
		return emailAddress;
	}

	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Set getUserPurchases() {
		return userPurchases;
	}

	public void setUserPurchases(Set userPurchases) {
		this.userPurchases = userPurchases;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", emailAddress=" + emailAddress + ", username=" + username + ", password=" + password
				+ "]";
	}

}

4. Create user-purchase.hbm.xml

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
	<class name="com.st.model.UserPurchase" table="user_purchase">
		<id name="purchaseId" column="iduser_purchase">
			<generator class="increment" />
		</id>

		<property name="price" type="float" column="price"></property>
		<property name="item" type="string" column="item"></property>
		
		<many-to-one name="user" class="com.st.model.User"
			fetch="select">
			<column name="user_id" not-null="true" />
		</many-to-one>

	</class>
</hibernate-mapping>

4. Create user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
	<class name="com.st.model.User" table="User">
		<id name="id">
			<generator class="increment" />
		</id>

		<property name="username" type="string" column="username"></property>
		<property name="password" type="string" column="password"></property>
		<property name="emailAddress" type="string" column="email_address"></property>
		
		<set name="userPurchases" table="user_purchase" inverse="true"
			lazy="true" fetch="select">
			<key>
				<column name="id" not-null="true" />
			</key>
			<one-to-many class="com.st.model.UserPurchase" />
		</set>
		
	
	</class>
</hibernate-mapping>

4. Update hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!--<property name="connection.url">jdbc:mysql://localhost:3306/sansa_ads</property> -->
		<property name="connection.url">jdbc:mysql://localhost:3306/training</property>
		<property name="connection.username">root</property>
		<property name="connection.password">password</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
		<!-- thread is the short name for org.hibernate.context.ThreadLocalSessionContext 
			and let Hibernate bind the session automatically to the thread -->
		<property name="current_session_context_class">thread</property>

		<!-- this will show us all sql statements -->
		<property name="hibernate.show_sql">true</property>

		<!-- mapping files -->


		<mapping resource="user.hbm.xml" />
		<mapping resource="user-purchase.hbm.xml" />



	</session-factory>
</hibernate-configuration>

4. Create a method in UserDAO Class

package com.st.dao;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.st.model.SocialClub;
import com.st.model.User;
import com.st.model.UserPurchase;

public class UserDAO {

	static Session session;

	static void createSession() {
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		session = sessionFactory.openSession();
	}


	public static boolean testCreateOneToMany() {
		boolean status = false;
		createSession();
		
		Transaction tx = session.beginTransaction();
		
		User user = new User();

		user.setEmailAddress("a@apple.com2");
		user.setUsername("a_user2");
		user.setPassword("a_pass2");
		session.save(user);
		
		UserPurchase userPurchase = new UserPurchase();
		userPurchase.setItem("Iphone");
		userPurchase.setPrice(695.00f);
		
		userPurchase.setUser(user);
		user.getUserPurchases().add(userPurchase);
		session.save(userPurchase);
		
		
		tx.commit();
		status = true;

		return status;

	}
	
	public static void main(String[] args) {


		testCreateOneToMany();

	}

}

10. That’s it. You should see an output like below to show that data has been inserted in the tables

Hibernate: select max(id) from User2
Hibernate: select max(iduser_purchase) from user_purchase
Hibernate: insert into User2 (username, password, email_address, id) values (?, ?, ?, ?)
Hibernate: insert into user_purchase (price, item, user_id, iduser_purchase) values (?, ?, ?, ?)

Also, Verify this in the database using a tool such as MySQL Workbench:

SELECT * FROM training.user_purchase;
'1','6','Iphone','695'

Posted in Coding Challenges, Computers and Internet, Interview Preparation, IT Jobs | Tagged | Leave a comment

Many to many relationship example using Hibernate – Step by Step Instructions

Many to many relationship using Hibernate can be super useful for any practical purposes. Here are step by step instructions on how to do the same:
In this example There is a many to many relationship between User and Social Club. A user can belong to many social clubs and a Social Club can have many users

Many to many relationship example using Hibernate

1. Create User Table

	CREATE DATABASE IF NOT EXISTS training; 
	CREATE TABLE IF NOT EXISTS
	training.User ( id INT NOT NULL AUTO_INCREMENT , 
	username VARCHAR(250) NOT NULL , 
	password VARCHAR(250) NOT NULL , 
	email_address VARCHAR(250) NULL ,
	PRIMARY KEY (id) , UNIQUE INDEX
	username_UNIQUE (username ASC) );

2. Create SocialClub Table

CREATE TABLE `training`.`socialclub` (
  `club_id` INT NOT NULL,
  `name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`club_id`));

3. Create User_SocialClub Table

CREATE TABLE `training`.`user_socialclub` (
  `user_id` INT NOT NULL,
  `club_id` INT NOT NULL,
  PRIMARY KEY (`user_id`,`club_id`),
  CONSTRAINT `fk_user_id`
    FOREIGN KEY (`user_id`)
    REFERENCES `training`.`User2` (`id`),
    
  CONSTRAINT `fk_club_id`
    FOREIGN KEY (`club_id`)
    REFERENCES `training`.`socialclub` (`club_id`)
)

4. Create SocialClub Class

package com.st.model;

import java.util.HashSet;
import java.util.Set;

//CREATE TABLE `training`.`socialclub` (
//		  `club_id` INT NOT NULL,
//		  `name` VARCHAR(45) NOT NULL,
//		  PRIMARY KEY (`club_id`));

public class SocialClub {
	private Integer clubId;
	private String name;
	private Set users = new HashSet();

	public SocialClub(String name) {
		
		
		this.name = name;
		
	}

	public SocialClub(Integer clubId, String name, Set users) {
		super();
		this.clubId = clubId;
		this.name = name;
		this.users = users;
	}

	public Integer getClubId() {
		return clubId;
	}

	public void setClubId(Integer clubId) {
		this.clubId = clubId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set getUsers() {
		return users;
	}

	public void setUsers(Set users) {
		this.users = users;
	}

}


5. Create User Class

package com.st.model;

import java.util.HashSet;
import java.util.Set;

/**
@author asinha
 *
 */
public class User {
	private int id;

	private String emailAddress;
	private String username;
	private String password;
	
	private Set userPurchases = new HashSet();
	
	
	private Set clubs = new HashSet();

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getEmailAddress() {
		return emailAddress;
	}

	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Set getUserPurchases() {
		return userPurchases;
	}

	public void setUserPurchases(Set userPurchases) {
		this.userPurchases = userPurchases;
	}

	public Set getClubs() {
		return clubs;
	}

	public void setClubs(Set clubs) {
		this.clubs = clubs;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", emailAddress=" + emailAddress + ", username=" + username + ", password=" + password
				+ "]";
	}

}

6. Create socialclub.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
	<class name="com.st.model.SocialClub" table="socialclub">
		<id name="clubId" column="club_id">
			<generator class="increment" />
		</id>


		<property name="name" type="string" column="name"></property>
		
		<set name="users" table="user_socialclub" inverse="true" lazy="true"
			fetch="select">
			<key>
				<column name="club_id" not-null="true" />
			</key>
			<many-to-many entity-name="com.st.model.User">
				<column name="user_id" not-null="true" />
			</many-to-many>
		</set>

	</class>
</hibernate-mapping>

7. Create user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
	<class name="com.st.model.User" table="User2">
		<id name="id" column="id">
			<generator class="increment" />
		</id>

		<property name="username" type="string" column="username"></property>
		<property name="password" type="string" column="password"></property>
		<property name="emailAddress" type="string" column="email_address"></property>
		
		<set name="userPurchases" table="user_purchase" inverse="true"
			lazy="true" fetch="select">
			<key>
				<column name="id" not-null="true" />
			</key>
			<one-to-many class="com.st.model.UserPurchase" />
		</set>
		
		<set name="clubs" table="user_socialclub" inverse="false"
			lazy="true" fetch="select" cascade="all">
			<key>
				<column name="user_id" not-null="true" />
			</key>
			<many-to-many entity-name="com.st.model.SocialClub">
				<column name="club_id" not-null="true" />
			</many-to-many>
		</set>
	</class>
</hibernate-mapping>

8. Update hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!--<property name="connection.url">jdbc:mysql://localhost:3306/sansa_ads</property> -->
		<property name="connection.url">jdbc:mysql://localhost:3306/training</property>
		<property name="connection.username">root</property>
		<property name="connection.password">password</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
		<!-- thread is the short name for org.hibernate.context.ThreadLocalSessionContext 
			and let Hibernate bind the session automatically to the thread -->
		<property name="current_session_context_class">thread</property>

		<!-- this will show us all sql statements -->
		<property name="hibernate.show_sql">true</property>

		<!-- mapping files -->


		<mapping resource="user.hbm.xml" />
		<mapping resource="user-purchase.hbm.xml" />
		<mapping resource="socialclub.hbm.xml" />


	</session-factory>
</hibernate-configuration>

9. Create a method in UserDAO Class

package com.st.dao;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.st.model.SocialClub;
import com.st.model.User;


public class UserDAO {

	static Session session;

	static void createSession() {
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		session = sessionFactory.openSession();
	}



	public static boolean testCreateManyToMany() {
		boolean status = false;
		createSession();
		
		Transaction tx = session.beginTransaction();
		User user = new User();

		user.setEmailAddress("a@apple.com2");
		user.setUsername("a_user2" + new Date().getTime());
		user.setPassword("a_pass2");
		//session.save(user);
		

		Set clubs = new HashSet(); 
		clubs.add(new SocialClub("CHESS CLUB"));
		clubs.add(new SocialClub("BOOK CLUB"));
		user.setClubs(clubs);
		session.save(user);
		
		
		tx.commit();
		status = true;

		return status;

	}
	
	public static void main(String[] args) {


		testCreateManyToMany();

	}

}

10. That’s it. You should see an output like below to show that data has been inserted in the tables

Hibernate: insert into User (username, password, email_address, id) values (?, ?, ?, ?)
Hibernate: insert into socialclub (name, club_id) values (?, ?)
Hibernate: insert into socialclub (name, club_id) values (?, ?)
Hibernate: insert into user_socialclub (user_id, club_id) values (?, ?)
Hibernate: insert into user_socialclub (user_id, club_id) values (?, ?)

Also, Verify this in the database using a tool such as MySQL Workbench:

SELECT * FROM training.socialclub;
club_id, name
'1','BOOK CLUB'
'2','CHESS CLUB'


SELECT * FROM training.user_socialclub;
user_id, club_id
'10','5'
'10','6'


Posted in Coding Challenges, Computers and Internet, IT Jobs | Tagged | Leave a comment

Test Your Java Skills

In case you are feeling itchy to asses your Java skills, here is a wonderful test. Please send me the solution at contact@sansatechnology.com – Will be happy to evaluate and send my comments.

Total Score: 120

1. [20 Marks] Create a method that will take a String as an input and return capitalized String in reverse.

E.g., Provided an input as abcd, it will return DCBA.

Call this method from main method and share the screen shot of input and output.

2. [20 Marks] Create a class called User.

User has following attributes:

firstName

lastName

username

password

Override toString and equals method

Call toString and equals method method from main method and share the screen shot of input and output.

3. [20 Marks] Create a method that reads list of User (User class is defined above) data from a file and returns an ArrayList of Users.

File looks like:

John, Wick, john_user, john123

<has many records>

Mark, Keaten, mark_user, m123

Call this method from main method and share the screen shot of input and output.

4. [20 Marks] How do you iterate through a HashMap. Build and example.

Call this method from main method and share the screen shot of input and output.

5. [20 Marks] Emulate the File System functionality. Allow user to list, rename, move, copy a file or folder

6. [20 Marks] Write an application that can take name, title and price of a movie and create a record in the database. User should also be allowed to choose a movie and edit its title and price. He can also delete the movie. He should also be able to display the list of movie by a search condition, such as show all movies whose title starts wit “T”.

Posted in Coding Challenges, Computers and Internet, Interview Preparation, IT Jobs, Uncategorized | Leave a comment

5 Ways to maximize your salary at the next Job

Maximize your salary

Maximize your salary

1. Research what are you worth – Look at the job portals, industry publications and check with your friends to get an idea on what your skills and experience is worth. e.g., It is not uncommon to see Java developers are paid anywhere from $40 to $90 or even higher depending upon their experience, skills and job locations.

2. Let the employer give you an offer first – You do not want to be the one who gives the number, as your salary expectation may be under par. Specially, employees coming from some outsourcing companies have salary on the lower side of the market rate. You should let the employer give you an offer first.

3. Ready to provide a counter offer – If your research suggests that you can get a better deal, be open to convey it in a polite manner. You should also have a strategy on what happens is the employer does not accept your counter offer.

4. Don’t be lazy – Sometimes people take whatever comes their way. Please spend some time to explore where you want your career to go and if the new compensation fits with your career path and goals.

5. Don’t overlook extras – If you can not get the base salary changed, explore if there is an opportunity to get better deals on bonus, insurance, healthcare, flexible work hours and other perks.

 

 

Posted in Uncategorized | Tagged , | Leave a comment

Questions Testers often ask

We get many questions asked from new Quality Assurance testers. I have compiled the list of top questions I hear from them:
1. What does the QA person do and where does it fit in the SDLC phase?
QA person tests a product before it can be released to production.
In a typical SDLC, here are typical steps:
1. Requirement Phase: Product Manager gets/ writes Biz Req Document
2. Analysis Phase: Tester creates test cases
3. Development Phase: Developers get use cases from BRD and write code
4. Validation Phase: Testers execute test cases and report bugs and revalidate the fixes

2. What’s a typical timeline of a Project?
Here is a hypothetical project:
Jan 1st, 2017: Project kicks off
March 1st, 2017: BRD is delivered
March 2nd onwards: You work on defining test cases
March 2nd to April end: Developers are starting to build
May 1st onwards: You can test

3. What is testing?
While there are many definitions of testing, a very simple definition that you look at the
actual result and compare it with the expected result. If both match your functionality is working, otherwise there is a bug.

4. What am I required to do in a Black box testing?
You should be able to do the following:
1. Should be able to convert use cases (BRD – Business Req Document) to test cases
2. You should know how to document and how to use Test Case repositories
3. If you have to report bugs, how and where to report bugs (Jira)
4. Automate – Use Selenium IDE to automate some use cases
5. Load testing – Load runner
6. SVN – How to check incheck out
7. Continuous Integration tool – Jenkins

5. What do you do as a White Box Tester?
In addition to the above, you will also work on
1. Looking at the code, and
2. Writing JUnit test cases

Posted in Uncategorized | Leave a comment

Java Files: Important Interview Coding Questions

One of our consultants recently went for an interview at “a very big company” in San Francisco, and she was asked to write Java implementation of File System function, such as list, create file, create folder etc.

We strongly recommend you to prepare yourself to be able to whiteboard these solutions for an interview.

Here is the solution (If you like this solution, please leave a comment – Thanks in advance):

 

/**
 * 
 */
package com.training.package3.q6;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * Emulate the following File system functions using File class: A. Create a
 * Folder (similar to mkdir command) B. Create a File C. Delete a Folder or File
 * (similar to rm command) D. Rename a File E. Read the content of a File and
 * Display the content (similar to cat command) F. Display the list of files and
 * folder under a Folder(similar to ls command)
 *
 * 
 */
public class FileSystemEmulator {

	/**
	 * A. Create a new folder at the base URL
	 * 
	 * @param baseURL
	 * @param folderName
	 * @return
	 */
	public boolean createFolder(String baseURL, String folderName) {
		File file = new File(baseURL, folderName);
		boolean status = false;
		try {
			status = file.mkdir();

		} catch (Exception e) {

			e.printStackTrace();
		}

		return status;
	}

	/**
	 * B. Create a File
	 * 
	 * @param baseURL
	 * @param folderName
	 * @return
	 */
	public boolean createFile(String baseURL, String fileName) {
		File file = new File(baseURL, fileName);
		boolean status = false;

		try {
			status = file.createNewFile();

		} catch (IOException e) {

			e.printStackTrace();
		}

		return status;
	}

	/**
	 * C. Delete a Folder or File (similar to rm command)
	 * 
	 * @param baseURL
	 * @param folderName
	 * @return
	 */
	public boolean deleteFile(String baseURL, String fileName) {
		File file = new File(baseURL, fileName);
		boolean status = false;

		try {
			status = file.delete();

		} catch (Exception e) {

			e.printStackTrace();
		}

		return status;
	}

	/**
	 * D. Rename a File
	 * 
	 * @param baseURL
	 * @param folderName
	 * @return
	 */
	public boolean renameFile(String baseURL, String fileName, String newName) {
		File file = new File(baseURL, fileName);
		boolean status = false;

		try {
			status = file.renameTo(new File(baseURL, newName));

		} catch (Exception e) {

			e.printStackTrace();
		}

		return status;
	}

	/**
	 * E. Read the content of a File and Display the content (similar to cat
	 * command)
	 * 
	 * @param baseURL
	 * @param folderName
	 * @return
	 */
	public boolean readAndDisplayContent(String baseURL, String fileName) {
		File file = new File(baseURL, fileName);
		boolean status = false;

		try {
			FileReader myFR = new FileReader(file);
			BufferedReader in = new BufferedReader(myFR);
			String str;

			while ((str = in.readLine()) != null) {

				System.out.println(str);
			}

			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return status;
	}

	/**
	 * F. Display the list of files and folder under a Folder(similar to ls
	 * command)
	 * 
	 * @param baseURL
	 * @param folderName
	 * @return
	 */
	public boolean listFilesFolder(String baseURL, String fileName) {
		File file = new File(baseURL, fileName);
		boolean status = false;

		try {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				System.out.println(files[i].getName());
			}

		} catch (Exception e) {

			e.printStackTrace();
		}

		return status;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		String baseURL = "/Users/amitesh.sinha/data";
		new FileSystemEmulator().createFolder(baseURL, "myFolder");
		new FileSystemEmulator().createFolder(baseURL, "myFile.txt");

		new FileSystemEmulator().readAndDisplayContent(baseURL, "myFile.txt");
		new FileSystemEmulator().listFilesFolder(baseURL, "myFile.txt");

		new FileSystemEmulator().deleteFile(baseURL, "myFile.txt");
		new FileSystemEmulator().renameFile(baseURL, "myFile.txt", "newName.txt");

	}
}

Posted in Coding Challenges, Computers and Internet, Interview Preparation, IT Jobs | Tagged , , | Leave a comment