Thursday, August 23, 2018

How to check whether operating system is 64 bit or 32bit?

What is 32 and 64 bit operating system?

The terms 32-bit and 64-bit refer to the way a computer's processor that is CPU, handles information. The 64-bit version of Windows handles large amounts of random access memory (RAM) more effectively than a 32-bit system. This refers to capability of processor that how much memory it can hold from RAM and it will help ro imrpove speed of processing.
To find out if your computer is running a 32-bit or 64-bit version of Windows in Windows 7 or Windows Vista, do the following:

How can I tell if my computer is running a 32-bit or a 64-bit version of Windows?



Open System by clicking the Start button The Start button, right-clicking Computer, and then clicking Properties.
Under System, you can view the system type.

Which version of Windows should I install: the 32-bit version or the 64-bit version?


To install a 64-bit version of Windows, you need a CPU that's capable of running a 64-bit version of Windows. The benefits of using a 64-bit operating system are most apparent when you have a large amount of random access memory (RAM) installed on your computer, typically 4 GB of RAM or more. In such cases, because a 64-bit operating system can handle large amounts of memory more efficiently than a 32-bit operating system, a 64-bit system can be more responsive when running several programs at the same time and switching between them frequently.

How to check whether CPU is 32 or 64 bit?



Go to search bar of windows and type system information.
Click on System information as shown in diagramme.
[caption id="attachment_416" align="alignnone" width="519"]Systeminformationsearch



System InformationSysteminformationHow to check whether CPU is 32 or 64 bit




System Type64bitsystemview RAM,Processor,System type details


On the right side of System Information, look for the System Type option under the Item column. The associated value, in the Value column, will tell you which type of CPU the computer has in it. If the System Type value includes "x86" in it, the CPU is 32-bit. If the System Type value includes "x64" in it, the CPU is 64-bit.

Reference:https://support.microsoft.com/en-in/help/15056/windows-7-32-64-bit-faq

How to install Java or JDK

Check your windows is 64bit or 32 bit?









Download .exe from below link based on your operating system is 32bit or 64 bit?


https://www.oracle.com/technetwork/java/javase/downloads/index.html
https://www.oracle.com/technetwork/java/javase/downloads/jdk10-downloads-4416644.html






Run Exe and follow steps


Once its installed you can run below command on command prompt and check whether its installed or not?




java -version
C:\Users\admin>java -version
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

C:\Users\admin>


  This means your java is installed successfully

Tuesday, August 21, 2018

Add and remove elements form array in javascript

Note:I have coded using typescript but javascript functions remains same

Declaration of Array:




numberoftasks: string[];


Adding elemnts in Array using push function



addtask() {
console.log('Adding Task: ' + this.form.value.task);
this.numberoftasks.push(this.form.value.task);
console.log(this.numberoftasks);
}


Output:["user1", "admin", "kavitha"]


Splice function with deletecount and start index 


deletetask(index) {
console.log('Deleting' + index);
this.numberoftasks.splice(index,1);
this.form.controls['task'].reset();
}

I am passing index as 0  in deletetask function and below is output.






Splice function Without deletecount


deletetask(index) {
console.log('Deleting' + index);
this.numberoftasks.splice(index);
this.form.controls['task'].reset();
}



If you wont pass any delete count then it will consider index as start index of elements needs to be deleted and it will delete all elements coming after this index.

e.g. if  index is 0  deletetask(0)

then it will delete entire array.


e.g. if  index is 1  deletetask(1)

then it will delete Elmets coming after index 1.

so out put will be like
["user1"]




Caused by: java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String;

Check all your Maven (or equivalent) dependencies and make sure that you - or most likely another dependency - are not pulling in a pre-3.1 version of the javax.servlet / servlet-api that may be taking precedence over what's in your Tomcat 8. If you've manually deployed, make sure you haven't manually copied any servlet-api JARs into Tomcat itself.


Below image you can see that old servlet API jar got added due to transitive dependency.







Solution:
Exclude servlet jar form dependency


Before:
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>

</dependency>


After

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>

</dependency>

A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]

Check all your Maven (or equivalent) dependencies and make sure that you - or most likely another dependency - are not pulling in a pre-3.1 version of the javax.servlet / servlet-api that may be taking precedence over what's in your Tomcat 8. If you've manually deployed, make sure you haven't manually copied any servlet-api JARs into Tomcat itself.


Below image you can see that old servlet API jar got added due to transitive dependency.







Solution:
Exclude servlet jar form dependency


Before:
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>

</dependency>


After

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>

</dependency>

Friday, August 17, 2018

Advantages of spring session

1)Supports horizontally and vertically scaled application
2)Easy to externalise session storage and management like redid ,memedcache,jdbc,hazelcast
3)Supports multiple session for same user.
4)Supports multiple session in same browser for different users.no need to logout and login by another user to start their session.
5)Easy to implement
6)Well Documented.

What is hazzlecast?

Hazzlecast is in memory data grid.
It's kind of clusters cache.which works with multiple running node and caters every request.
In this every node is working as master and serving requests.
All nodes are working as team so better performance is delivered.
Hazzlecast runs on jvm so it's easy to integrate with java.

Due to in memory data grid and clustered cache it will improve performance.This is mostly getting used for low latency high throughout softwares.

Wednesday, August 15, 2018

Build "Hello World Application" with Angular 1+

Build "Hello World Application" with Angular 1+


Prerequisite:
Download AngularJS javascript file from Angular officail website https://angularjs.org/

or 
Refer CDN link to import  angular.min.js in your html page. 


Code :



<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
<p>Enter "World" in below input box</p>
<p>Name : <input type="text" ng-model="firstname" placeholder="Enter 'World'" "></p>
<h1>Hello  {{firstname}}</h1>

</div>

</body>
</html>


Output:




Oracle Coherence

What's is it?

It's in memory data grid use for high throughout and low latency applications.
This product is devlopement by Oracle.


Below are advantages of using this
1) High throughput and low latency
2) no single point of failure
3) High availability of data
4) Easy to adopt
5) Well documented

Thjs is a cache which runs by using RAM memory and forming distributed grid.

Illegal Character when trying to compile java code ,getting illegal character: '\u0000'

This error will occur if you have unwanted character other than UTF-8 in your jave file .

To resolve this open your file in notepad++

Select encoding type as mentioned in below image










then it will show you unwanted characters.


Remove all these characters from file and save file.
Again Compile same file .This time you should get error while compiling file.

Monday, August 13, 2018

Automate Tomcat Deployment for maven project

Scala Setup and first Application

Hello All,

I am also new to scala so I am also trying to do setup for do setup of scala hope it will help you.

Best way to learn any language is to download its IDE,It will save your manual efforts.

second way is to use scala binary and run your application from command prompt.

I am going to use eclipse ide for scala.

1)You can download it from the scala's official site

http://scala-lang.org/download/

2)Download file and unzip on your machine.

3)Run eclipse.exe file from \scala-SDK-4.0.0-vfinal-2.11-win32.win32.x86\eclipse

4)It will ask you for workspace,Create any folder and give its path.

e.g.c:\scala\testapplication

5)Create your first scall application from

File=>New=>Other=>scala application

6)Give class name in popup window

e.g.Hello.scala

7)add prinln("Hello World") in that file and run it.

e.g.

package com.sagar.basic

object Hello extends App {

println("Hello World");

}

Output would be: Hello World

Scala Hello World Example

Hello All,

I am also new to scala so I am also trying to do setup for do setup of scala hope it will help you.

Best way to learn any language is to download its IDE,It will save your manual efforts.

second way is to use scala binary and run your application from command prompt.

I am going to use eclipse ide for scala.

1)You can download it from the scala's official site

http://scala-lang.org/download/

2)Download file and unzip on your machine.

3)Run eclipse.exe file from \scala-SDK-4.0.0-vfinal-2.11-win32.win32.x86\eclipse

4)It will ask you for workspace,Create any folder and give its path.

e.g.c:\scala\testapplication

5)Create your first scall application from

File=>New=>Other=>scala application

6)Give class name in popup window

e.g.Hello.scala

7)add prinln("Hello World") in that file and run it.

e.g.

package com.sagar.basic

object Hello extends App {

println("Hello World");

}

Output would be: Hello World

Scala Setup and First Example

Hello All,

I am also new to scala so I am also trying to do setup for do setup of scala hope it will help you.

Best way to learn any language is to download its IDE,It will save your manual efforts.

second way is to use scala binary and run your application from command prompt.

I am going to use eclipse ide for scala.

1)You can download it from the scala's official site

http://scala-lang.org/download/

2)Download file and unzip on your machine.

3)Run eclipse.exe file from \scala-SDK-4.0.0-vfinal-2.11-win32.win32.x86\eclipse

4)It will ask you for workspace,Create any folder and give its path.

e.g.c:\scala\testapplication

5)Create your first scall application from

File=>New=>Other=>scala application

6)Give class name in popup window

e.g.Hello.scala

7)add prinln("Hello World") in that file and run it.

e.g.

package com.sagar.basic

object Hello extends App {

println("Hello World");

}

Output would be: Hello World

Scala String interpolation

Introduction

Starting in Scala 2.10.0, Scala offers a new mechanism to create strings from your data: String Interpolation. String Interpolation allows users to embed variable references directly in processedstring literals. Here’s an example:
  1. val name = "James"
  2. println(s"Hello, $name") // Hello, James
In the above, the literal s"Hello, $name" is a processed string literal. This means that the compiler does some additional work to this literal. A processed string literal is denoted by a set of characters precedding the ". String interpolation was introduced by SIP-13, which contains all details of the implementation.

Usage

Scala provides three string interpolation methods out of the box: s, f and raw.

The s String Interpolator

Prepending s to any string literal allows the usage of variables directly in the string. You’ve already seen an example here:
  1. val name = "James"
  2. println(s"Hello, $name") // Hello, James
Here $name is nested inside an s processed string. The s interpolator knows to insert the value of the name variable at this location in the string, resulting in the string Hello, James. With the sinterpolator, any name that is in scope can be used within a string.
String interpolators can also take arbitrary expressions. For example:
  1. println(s"1 + 1 = ${1 + 1}")
will print the string 1 + 1 = 2. Any arbitrary expression can be embedded in ${}.

The f Interpolator

Prepending f to any string literal allows the creation of simple formatted strings, similar to printfin other languages. When using the f interpolator, all variable references should be followed by aprintf-style format string, like %d. Let’s look at an example:
  1. val height = 1.9d
  2. val name = "James"
  3. println(f"$name%s is $height%2.2f meters tall") // James is 1.90 meters tall
The f interpolator is typesafe. If you try to pass a format string that only works for integers but pass a double, the compiler will issue an error. For example:
  1. val height: Double = 1.9d
  2. scala> f"$height%4d"
  3. <console>:9: error: type mismatch;
  4. found : Double
  5. required: Int
  6. f"$height%4d"
  7. ^
The f interpolator makes use of the string format utilities available from Java. The formats allowed after the % character are outlined in the Formatter javadoc. If there is no % character after a variable definition a formatter of %s (String) is assumed.

The raw Interpolator

The raw interpolator is similar to the s interpolator except that it performs no escaping of literals within the string. Here’s an example processed string:
  1. scala> s"a\nb"
  2. res0: String =
  3. a
  4. b
Here the s string interpolator replaced the characters \n with a return character. The rawinterpolator will not do that.
  1. scala> raw"a\nb"
  2. res1: String = a\nb
The raw interpolator is useful when you want to avoid having expressions like \n turn into a return character.
In addition to the three default string interpolators, users can define their own.
example:
package com.sagar.basic
import scala.math._
object Hello extends App {
println("Hello World");
//String Interpolation Example
val Tau = Pi * 2
println(s"Valie of tau is $Tau");
//String Interpolation example with s & f
println("Result for string interpolation with s:" + s"Happy $Tau Day")
println("Result for string interpolation with f:" + f"Happy $Tau%2.2f Day")
//String Formating
printf("Now you have %.7f problems.", Math.nextAfter(2.0, 3))
}

Primary and foreign Key Altering Issue /How to rename constraint

We can not create/alter same constraint on same column in table if the same constraint is all ready present in table for same column.

Note:Here I am talking about constraint not about key.

Primary Key Example :

Step 1:Create supplier table

CREATE TABLE supplier

(

supplier_id numeric(10) not null,

supplier_name varchar2(50) not null,

contact_name varchar2(50),

CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name) );

Step 2:Check table is created or not?

select * from supplier

Step 3:Try to alter primary key constraint with different name .It will throw error.

ALTER TABLE supplier

ADD CONSTRAINT supplier_pk1 PRIMARY KEY (supplier_id, supplier_name);

We can conclude that we can not alter or add constraint if it is present in table for same column.Table can have only one primary key and primary constraint in table.

Foreign Key Example :

Step 1:Create supplier table

CREATE TABLE supplier

(

supplier_id numeric(10) not null,

supplier_name varchar2(50) not null,

contact_name varchar2(50),

CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name) );

Step 2:Check table is created or not?

select * from supplier

Step 3:Create second table .

CREATE TABLE Orders

(

supplier_id numeric(10) not null,

supplier_name varchar2(50) not null,

contact_name varchar2(50)

);

Step 4:Check table is created or not?

select * from Orders

Step 5:Add constraint to orders tables

ALTER TABLE Orders

ADD CONSTRAINT fk_supplier

FOREIGN KEY (supplier_id, supplier_name)

REFERENCES supplier(supplier_id, supplier_name);

Step 5:Check table constraints

desc Orders

Step 6:Add another constraint with another name  to orders tables

ALTER TABLE Orders

ADD CONSTRAINT fk_supplier1

FOREIGN KEY (supplier_id, supplier_name)

REFERENCES supplier(supplier_id, supplier_name);

This will throw an error.

We can conclude that we can not alter or add constraint if it is present in table for same column.In table orders fk_supplier constraint is allready present so if we try to add another constraint with name fk_supplier1. It wont allow you.

Solution for above issues:

For resolving this issue you have to use rename query.

ALTER TABLE Orders RENAME CONSTRAINT fk_supplier TO fk_supplier1

This query will allow you to rename constraint with new name.

Note:If you want to check constraint in table you can use following query.

Select * from all_constraints where table_name ='ORDERS'

Scala Basics And Setup Environment

Hello All,

I am also new to scala so I am also trying to do setup for do setup of scala hope it will help you.

Best way to learn any language is to download its IDE,It will save your manual efforts.

second way is to use scala binary and run your application from command prompt.

I am going to use eclipse ide for scala.

1)You can download it from the scala's official site

http://scala-lang.org/download/

2)Download file and unzip on your machine.

3)Run eclipse.exe file from \scala-SDK-4.0.0-vfinal-2.11-win32.win32.x86\eclipse

4)It will ask you for workspace,Create any folder and give its path.

e.g.c:\scala\testapplication

5)Create your first scall application from

File=>New=>Other=>scala application

6)Give class name in popup window

e.g.Hello.scala

7)add prinln("Hello World") in that file and run it.

e.g.

package com.sagar.basic

object Hello extends App {

println("Hello World");

}

Output would be: Hello World

How to Install the Java Software Development Kit ,Install JDk

1.Download the latest version of the *Java JDK from Sun Microsystems.

2.Install the installer file.

3. IN C:/Programe files it will create java folder.

4.After the installer is finished, open run by clicking Start > Run... or by typing Windows Key + R.

5. In the text box, type "cmd" and click "OK".

6. Type Java -version in command prompt

It will show below result

C:\>java -version
java version "1.7.0_03"
Java(TM) SE Runtime Environment (build 1.7.0_03-b05)
Java HotSpot(TM) Client VM (build 22.1-b02, mixed mode, sharing)

Note:If this command is not working then setup environment variable and try again

Windows XP
Select Start, select Control Panel. double click System, and select the Advanced tab.
Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. ...
In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable.
add your jdk path in PATH environment variable e.g. C:/Programme Files/Java/Jdk

Scala Hello World Example With object class

Guys/Girls I am using Eclipse IDE for Scala for development

You can easily download this from below URL

http://scala-ide.org/download/current.html

Now lets start with our first example.As usual it Hello World program.

Please follow below steps to create and execute first class

1)GO to file =>New=>Select "Scala Class"

2)Give name as HelloWorld.scala

3) Inside Class use method println to write hello world.

code will look like

class HelloWorldWithObject {
println("Hello World");
}

4)We need to run this class ut we can not run this class without main method so we are going to create one object having name hello

code for object is

object hello {

def main(args: Array[String]): Unit = {
var name = new HelloWorldWithObject();
}
}

5)The complete class will look like
package com.sagar.basic

class HelloWorldWithObject {
println("Hello World");
}
object hello {

def main(args: Array[String]): Unit = {
var name = new HelloWorldWithObject();
}
}

7)Right click inside class and run it as scala application

it will print below output:

Hello World

Scala Hello World Example With Extending App trait

Guys/Girls I am using Eclipse IDE for Scala for development

You can easily download this from below URL

http://scala-ide.org/download/current.html

Now lets start with our first example.As usual it Hello World program.

Please follow below steps to create and execute first class

Step:1)GO to file =>New=>Select "Scala Class"

Step:2)Give name as HelloWorld.scala

Step:3) Inside Class use method println to write hello world.

code will look like

class HelloWorldWithObject {
println("Hello World");
}

Step:4)Extend this class with App trait

NOte:What IS App trait,Below is small documentation of App
scala.App
The App trait can be used to quickly turn objects into executable programs. Here is an example:

object Main extends App {
  Console.println("Hello World: " + (args mkString ", "))
}


Here, object Main inherits the main method of App.

args returns the current command line arguments as an array.

Step:5)Complete class will look like

package com.sagar.basic

class HelloWordlWithApp extends App {
println("Hello World");

}

Step:6) Right click inside class and run it as scala application it will print below output:

Hello World

Multiple variable initialization with Scala

Scala has good facility to initialize mulitple variables at a same time.

Please go throught below example it is pretty straight forward just copy and paste it and run it.

For basic steps like creation of class please follow first two steps of below example

https://sagarthakare1.wordpress.com/2015/04/17/scala-hello-world-example-with-object-class/

package com.sagar.basic

object MultipleVariableIntialisation extends App{
private val a,b,c=2;
println("Value of a:"+a);
println("Value of b:"+b);
println("Value of c:"+c);

}

Hibernate and Spring Integration

Now days everyone is interested in building smart application with ORM tools +Spring.Here we are going to do configuration of Hibernate with Spring.

Steps 1:Create Maven project having name as hibernate.

Steps 2:Weneed Jar file of HIbernate and Spring for integration.Add required dependencies in pom.xml file.




org.springframework
spring-jdbc
${spring.version}


cn.guoyukun.jdbc
oracle-ojdbc6
11.2.0.3.0



org.hibernate
hibernate-entitymanager
${hibernate.version}


org.springframework
spring-orm
${spring.version}


org.hibernate
hibernate-core
${hibernate.version}


org.hibernate
hibernate-ehcache
4.3.7.Final


com.github.dblock.waffle
waffle-jna
1.6


org.springframework
spring-core
${spring.version}




org.springframework
spring-context
${spring.version}


org.springframework
spring-web
${spring.version}


org.apache.httpcomponents
httpmime
${httpcomponents.httpmime}


org.springframework
spring-webmvc
${spring.version}


commons-lang
commons-lang
${commons-lang.commons-lang.version}


org.apache.httpcomponents
httpclient
${httpcomponents.httpclient}


commons-logging
commons-logging




org.daisy.libs
commons-httpclient
${commons.httpclient}


commons-logging
commons-logging




org.springframework
spring-oxm
${spring.oxm}
sources


jaxen
jaxen
${jaxen}


org.springframework.ws
spring-xml
${spring.xml}



commons-logging
commons-logging





1.1.6
4.3.5
4.3.5

3.1.0
1.7
4.0.5.RELEASE
4.3.5.Final
3.0.5.RELEASE
2.3
2.6
4.3.5
2.5
2.2.0.RELEASE

Step 3: Create Employee class and map this class with the table which you want to create .Here we have used some annotation to make our work easy.

If you are interested to find what these annotation exactly doing then please use below link for more details.

https://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/

Employee.Java class will contain below code.

package com.javatpoint;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name= "." +
"")
public class Employee {
@Id
private int id;
private String firstName,lastName;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
Step 4:Create application context file and having name as "applicationContext.xml"

a)Add datasource details in application context file







please replace value of each property e.g. replace ${db.username} with username of your database .e.g out database have user as scott so property will look like



b)we also need to setup hibernates session factory object and that will looks like

FactoryBean that creates a Hibernate SessionFactory. This is the usual way to set up a shared Hibernate SessionFactory in a Spring application context; the SessionFactory can then be passed to Hibernate-based DAOs via dependency injection.

please read below document for more details o:

http://docs.spring.io/spring-framework/docs/3.2.13.RELEASE/javadoc-api/org/springframework/orm/hibernate3/LocalSessionFactoryBean.html

your complete applicationContext.xml file will looks like.



xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">













com.javatpoint.Employee





org.hibernate.dialect.Oracle10gDialect
false
update
true
true
org.hibernate.cache.ehcache.EhCacheRegionFactory







Step 5:We are using annotation so we need to pass annotated classes so added Employee class in configuration of sessionFactory bean.Allready covered in step 4

e.g.





com.javatpoint.Employee





org.hibernate.dialect.Oracle10gDialect
false
update
true
true
org.hibernate.cache.ehcache.EhCacheRegionFactory



Step 6:For communicating with Database we need one Dao class.We will use sessionFactory in that class (EmployeeDaoImpl.java)and it will look like

package com.javatpoint.impl;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.javatpoint.Employee;
@Component
public class EmployeeDaoImpl {

@Autowired
SessionFactory sessionFactory;

public Long save(Employee t) {
try {
Long id = (Long) sessionFactory.getCurrentSession().save(t);
return id;
} catch (RuntimeException re) {
throw re;
}
}

}

Step 7:For running application will need one java class having main method.

package com.javatpoint.impl;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.javatpoint.Employee;

public class InsertTest {
public static void main(String[] args) {
Employee em= new Employee();
em.setFirstName("Sagar");
em.setId(3);

ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDaoImpl employeeDaoImpl=(EmployeeDaoImpl)context.getBean("employeeDaoImpl");
}

}

Step 8:Run main method of InsertTest class

During loading of application context session factory clss will check that whether this table is present or not in database .If table is not created sessionfactory will create table.

Note:   You can enable many hibernate properties like automatic table creation by hbm2ddl.auto ,Just add it in applciationcontext file .We have allready added them in file.so need to worry if table is not present in your databse.

 "hibernate.dialect">org.hibernate.dialect.Oracle9Dialect                 "hibernate.hbm2ddl.auto">update                  "hibernate.show_sql">true

Spring Hello World Example with Maven

Step  1:Create Maven Project

Create maven project and give name  as springExamples.

Note:Use eclipse for this and install maven plugin to get started.YOu can easily get steps of installation on google .just type" m2e plugin for eclipse" in google.

Step 2:  Maven Project Structure

Your folder structure will have pom.xml file .

Step 3: Spring Dependencies

We will need spring jar to start .

Add below dependency in pom.xml

org.springframework

spring-core

4.1.6.RELEASE

Step 4: Maven Clean Install

Run Maven clean install so it will download Jar from maven repository.Run this from command prompt using command mvn clean install or you can run it from eclipse

After running this your project will have  spring.jar

You will able to see spring jar.

Step 5:HelloWorld.java

Create HelloWorld.java class

File:HelloWorld.java

public class HelloWorld {

private String name;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public void display ()

{

System.out.println(this.getName());

}

}

Step 6: Create ApplicationContext.xml 

Create ApplicationContext.xml  file for spring configuration.

File:ApplicationCOntext.xml

"http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

"helloBean" class="HelloWorld">

"name" value="HelloWorld :I am able to run project" />

Step 7: Create SpringRunner.java

Create SpringRunner.java class to run this small spring application

File:SpringRunner.java

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringRunner {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

ApplicationContext context = new ClassPathXmlApplicationContext(

"ApplicationContext.xml");

HelloWorld obj = (HelloWorld) context.getBean("helloBean");

obj.display();

}

}

Step 8: Output

Right click in SpringRunner class and Run as Java Application

It will print

HelloWorld :I am able to run project

Read/Fetch/Print only getter methods of any class with Introspector and PropertyDescriptor

Through reflection we can read any property of java class but its difficult to fetch only required methods.

I found one new way to do it.

please follow below mentioned example and run it

Step 1: Create Employee.java

public class Employee implements java.io.Serializable{
private int id;
private String name;

public Employee(){}

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

public int getId(){return id;}

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

public String getName(){return name;}

}

Step 2: Create HelloWorldRef

import java.beans.Introspector;
import java.beans.PropertyDescriptor;

public class HelloWorldRef {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
try {
for(PropertyDescriptor propertyDescriptor :
Introspector.getBeanInfo(Employee.class,Object.class).getPropertyDescriptors()){

// propertyEditor.getReadMethod() exposes the getter
// btw, this may be null if you have a write-only property
System.out.println(propertyDescriptor.getReadMethod());
}
}catch(Exception e){
e.printStackTrace();
}
}
}

Step 3:Run HelloWorldRef class

you will get below output

Hello World!
public int com.technical.examples.Docker.Employee.getId()
public java.lang.String com.technical.examples.Docker.Employee.getName()

Here we got just getter methods from employee class.

Basic Dozer Example

Many times in programming language we are copying attributes of one class to other class.

Most of the time we are doing same thing more than one places so its repeating code. Dozer has provided API to do same ting in very easy way.

Step 1: Create Project

Create Spring Project.Please refer below link to create project

https://sagarthakare1.wordpress.com/2015/04/23/spring-hello-world-example-with-maven/?preview=true&preview_id=38&preview_nonce=1e8a5eead7

Step 2:Create Employee class

File:Employee.java

package com.javatpoint;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

public class Employee {
private int id;
private String firstName,lastName;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}

}

Step:4 Create Student class

File:Student.java

package com.javatpoint;

public class Student {

private String name;

public String getName() {
return name;
}

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

}

Step 4:Create DozerMapping file

File:DozerMapping.xml

<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">

<configuration>
<stop-on-errors>true</stop-on-errors>
<date-format>MM/dd/yyyy HH:mm</date-format>
<wildcard>true</wildcard>
</configuration>

<mapping>
<class-a>com.javatpoint.Student</class-a>
<class-b>com.javatpoint.Employee</class-b>
<field>
<a>name</a>
<b>firstName</b>
</field>

</mapping>

</mappings>

Step 5: Create Bean

We are creating bean with spring so we will add this in applicationContext.xml file.

File:applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">

<context:annotation-config/>
<context:component-scan base-package="com.javatpoint" />

<bean id="mapper" class="org.dozer.DozerBeanMapper">
<property name="mappingFiles">
<list>
<value>DozerMapping.xml</value>

</list>
</property>
</bean>
</beans>

Step 6 :Create runner class

Create class to run this code

I have create insertTest class

File:InsertTest.java

package com.javatpoint.impl;

import java.util.Arrays;

import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.javatpoint.Employee;
import com.javatpoint.Student;

public class InsertTest {
public static void main(String[] args) {

Student s= new Student();
s.setName("Alexander");
ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
Mapper mapper=(DozerBeanMapper)context.getBean("mapper");

//DozerBeanMapper mapper = new DozerBeanMapper(Arrays.asList(new String[]{"DozerMapping.xml"}));
Employee employee=mapper.map(s, Employee.class);
System.out.println("Name Mapped by dozer is:"+employee.getFirstName());

}

}

Step 7 :Output

You will get below output after running code

Name Mapped by dozer is:Alexander

Setup Selenium Webdriver

Step 1:Create Spring Project

follow steps mentioned in below page to create project

https://sagarthakare1.wordpress.com/2015/04/23/spring-hello-world-example-with-maven/

Step 2:Download Jar

Download selenium webdriver from below link for java

This download comes as a ZIP file named "selenium-2.25.0.zip". For simplicity, extract the contents of this ZIP file on your C drive so that you would have the directory "C:\selenium-2.25.0\". This directory contains all the JAR files that we would later import on Eclipse.

http://docs.seleniumhq.org/download/

Step 3:Right-click on myproject and select Properties

Step 4:On the Properties dialog, click on "Java Build Path".

Step 5:Click on the Libraries tab, and then click "Add External JARs.."

Step 6:Navigate to C:\selenium-2.25.0\ (or any other location where you saved the extracted contents of "selenium-2.25.0.zip" in step

Add all the JAR files inside and outside the "libs" folder.

Step 7:Finally, click OK and we are done importing Selenium libraries into our project.

You are ready to use selenium webdriver

Create Core Java project with eclipse

Opening the New Java Project wizard

The New Java Project wizard can be used to create a new java project. There are many ways to open this wizard:
  • By clicking on the File menu and choosing New > Java Project
  • By right clicking anywhere in the Project Explorer and selecting New > Java Project
  • By clicking on the New button in the Tool bar and selecting Java Project
  • Steps

    1.  

Using the New Java Project wizard

The New Java Project Wizard has two pages.
On the first page:
  • Enter the Project Name
  • Select the Java Runtime Environment (JRE) or leave it at the default
  • Select the Project Layout which determines whether there would be a separate folder for the sources code and class files. The recommended option is to create separate folders for sources and class files.
ou can click on the Finish button to create the project or click on the Next button to change the java build settings.
On the second page you can change the Java Build Settings like setting the Project dependency (if there are multiple projects) and adding additional jar files to the build path.

Viewing the newly created project

The package explorer shows the newly created Java project. The icon that represents a Project is decorated with a "J" to show that it is a Java Project. The folder icon is decorated to show that it is a java source folder.

Cucumber Basics

Cucumber Introduction:

Cucumber is a tool based on Behavior Driven Development (BDD) framework which is used to write acceptance tests for web application. It allows automation of functional validation in easily readable and understandable format (like plain English) to Business Analysts, Developers, Testers, etc.
Cucumber tools also support Behavior Driven Development (BDD).It offers a way to write tests that anybody can understand, regardless of their technical knowledge.
In BDD, users (business analysts, product owners) first write scenarios or acceptance tests that describes the behavior of the system from the customer's perspective, for review and sign-off by the product owners before developers write their codes.
Cucumber use Ruby programming language.


What are the benefits?
  1. It is helpful to involve business stakeholders who can't easily read code
  2. Cucumber focuses on end-user experience
  3. Style of writing tests allow for easier reuse of code in the tests
  4. Quick and easy set up and execution
  5. Efficient tool for testing
Cucumber feature files can serve as a good document for all. There are many other tools like JBehave which also support BDD framework. Initially Cucumber was implemented in Ruby and then extended to Java framework. Both the tools support native JUnit.
Behavior Driven Development is extension of Test Driven Development and it is used to test the system rather than testing the particular piece of code. We will discuss more about the BDD and style of writing BDD tests.
Cucumber can be used along with Selenium, Watir, and Capybara etc. Cucumber supports many other languages like Perl, PHP, Python, .Net etc. In this tutorial we will concentrate on Cucumber with Java as a language.

Cucumber Basics:

In order to understand cucumber we need to know all the features of cucumber and its usage.
#1) Feature Files:
Feature files are essential part of cucumber which is used to write test automation steps or acceptance tests. This can be used as live document. The steps are the application specification. All the feature files ends with .feature extension.
Sample feature file:
Feature: Login Functionality Feature
In order to ensure Login Functionality works,
I want to run the cucumber test to verify it is working
Scenario: Login Functionality
Given user navigates to abc.COM
When user logs in using Username as “USER” and Password “PASSWORD”
Then login should be successful
Scenario: Login Functionality
Given user navigates to abc.COM
When user logs in using Username as “USER1″ and Password “PASSWORD1″
Then error message should be thrown
#2) Feature:
This gives information about the high level business functionality (Refer to previous example) and the purpose of Application under test. Everybody should be able to understand the intent of feature file by reading the first Feature step. This part is basically kept brief.
#3) Scenario:
Basically a scenario represents a particular functionality which is under test. By seeing the scenario user should be able to understand the intent behind the scenario and what the test is all about. Each scenario should follow given, when and then format. This language is called as “gherkin”.
  1. Given: As mentioned above, given specifies the pre-conditions. It is basically a known state.
  2. When: This is used when some action is to be performed. As in above example we have seen when the user tries to log in using username and password, it becomes an action.
  3. Then: The expected outcome or result should be placed here. For Instance: verify the login is successful, successful page navigation.
  4. Background: Whenever any step is required to perform in each scenario then those steps needs to be placed in Background. For Instance: If user needs to clear database before each scenario then those steps can be put in background.
  5. And: And is used to combine two or more same type of action.
Example:
Feature: Login Functionality Feature
Scenario: Login Functionality
Given user navigates to abc.COM
When user logs in using Username as “USER”
And password as “password”
Then login should be successful
And Home page should be displayed
Example of Background:
Background:
Given user logged in as databases administrator
And all the junk values are cleared
#4) Scenario Outline:
Scenario outlines are used when same test has to be performed with different data set. Let’s take the same example. We have to test login functionality with multiple different set of username and password.
Feature: Login Functionality Feature
In order to ensure Login Functionality works,
I want to run the cucumber test to verify it is working
Scenario Outline: Login Functionality
Given user navigates to abc.COM
When user logs in using Username as <username> and Password <password>
Then login should be successful
Examples:
|username         |password          |
|Tom                     |password1        |
|Harry                   |password2        |
|Jerry                    |password3        |
Note:
  1. As shown in above example column names are passed as parameter to When statement.
  2. In place of Scenario, you have to use Scenario Outline.
  3. Examples are used to pass different arguments in tabular format. Vertical pipes are used to separate two different columns. Example can contain many different columns.
#5) Tags:
Cucumber by default runs all scenarios in all the feature files. In real time projects there could be hundreds of feature file which are not required to run at all times.
For instance: Feature files related to smoke test need not run all the time. So if you mention a tag as smokeTest in each feature file which is related to smoke test and run cucumber test with @SmokeTest tag . Cucumber will run only those feature files specific to given tags. Please follow the below example. You can specify multiple tags in one feature file.
Example of use of single tags:
@SmokeTest

Feature: Login Functionality Feature
In order to ensure Login Functionality works,
I want to run the cucumber test to verify it is working
Scenario Outline: Login Functionality
Given user navigates to abc.COM
When user logs in using Username as <username> and Password <password>
Then login should be successful

Cucumber Setup with Maven

Enable Cucumber in Java project

1) Enable using maven

Create Maven project and Add below dependency in pom.xml
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<scope>test</scope>
<version>1.0.11</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-jvm</artifactId>
<version>1.0.11</version>
<type>pom</type>
</dependency>

2) Download and install cucumber plugin for eclipse

http://marketplace.eclipse.org/content/cucumber-jvm-eclipse-plugin

3) Create feature file in your project

To create a feature file

    1. In the Project tool window, right-click a directory, where feature files should be created.
    2. On the context menu of the target directory, choose New | File, and in the New File dialog box, type <name>.feature.

4) Write Steps in feature file

Feature: Login 

  @smoke
  Scenario: Login Functionality
    Given User details
    When UI submits the User data
    Then return Message user is authenticated

5) We have cucumber plugin installed in eclipse IDE so right click on feature file and run it.

It will show you below output on console
WARNING: Cucumber-JVM's --format option is deprecated. Please use --plugin instead.
1 Scenarios (1 undefined)
3 Steps (3 undefined)
0m0.000s
You can implement missing steps with the snippets below:
@Given("^User details$")
public void user_details() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@When("^UI submits the User data$")
public void ui_submits_the_User_data() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Then("^return Message user is authenticated$")
public void return_Message_user_is_authenticated() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
Undefined step: Given User details
Undefined step: When UI submits the User data
Undefined step: Then return Message user is authenticated
1 scenario (0 passed)
3 steps (0 passed)
Process finished with exit code 0
We have not implemented steps mentioned in feature file so thats why it is giving this error.

Step 6) Copy methods present below "You can implement missing steps with the snippets below:" string in console.

Create new class in same  package and paste them in that.
Will create TestSuit.java dn paste it.
package features;

import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class TestSuit {

    @Given("^User details$")
    public void user_details() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }

    @When("^UI submits the User data$")
    public void ui_submits_the_User_data() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }

    @Then("^return Message user is authenticated$")
    public void return_Message_user_is_authenticated() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }



}

Step 7) Again right click in feature file and run it .

Now it will give below error because we have not implemented above methods and they are still having
 throw new PendingException();
in theire methods
WARNING: Cucumber-JVM's --format option is deprecated. Please use --plugin instead.
Skipped step
Skipped step
Skipped step
1 scenario (0 passed)
3 steps (0 passed)
1 Scenarios (1 pending)
3 Steps (2 skipped, 1 pending)
0m0.742s
cucumber.api.PendingException: TODO: implement me
at features.TestSuit.user_details(TestSuit.java:13)

Step 8) Either implement your logic in these methods or for just testing purpose remove these exception from methods.

now code will look like
package features;

import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class TestSuit {

    @Given("^User details$")
    public void user_details() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        
    }

    @When("^UI submits the User data$")
    public void ui_submits_the_User_data() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
       
    }

    @Then("^return Message user is authenticated$")
    public void return_Message_user_is_authenticated() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
       
    }



}

Step 9) Run feature file again

you will get below output
1 Scenarios (1 passed)
3 Steps (3 passed)
0m0.559s
1 scenario (1 passed)
3 steps (3 passed)
Process finished with exit code 0
Now in this steps all the steps are passed.
We are done with cucumber integration.

Cucumber with Junit and Cucumber Reporting

Please follow initial steps mentioned on below link for cucumber integration with Maven.


https://sagarthakare1.wordpress.com/2015/05/15/cucumber-setup-with-maven/

Once you are done with all steps then follow below steps

1) Add Junit Jar

Add Junit jar dependency in your Pom.xml file or add this jar to your project build path.

2) Create Junit

Create TestRunner class in same package and cucumber option on class using annotation
package features;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(format = {
        "pretty",
        "json:target_json/cucumber.json",
        "junit:taget_junit/cucumber.xml"
})
public class TestRunner {

}

3) Run junit

Right click in class and run as Junit.
you will get below output
Feature: Login
@smoke
Scenario: Login Functionality # features/login.feature:4
Given User details # TestSuit.user_details()
When UI submits the User data # TestSuit.ui_submits_the_User_data()
Then return Message user is authenticated # TestSuit.return_Message_user_is_authenticated()
1 Scenarios (1 passed)
3 Steps (3 passed)
0m0.841s
Process finished with exit code 0

4) Cucumber Reporting

We have added below on Junit class
@CucumberOptions(format = {
        "pretty",
        "json:target_json/cucumber.json",
        "junit:taget_junit/cucumber.xml"
})
It will generate reports in target_json and taget_junit folder,
Below is output from cucumber.xml file
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<testsuite failures="0" name="cucumber.runtime.formatter.JUnitFormatter" skipped="0" tests="1" time="0.84123">
<testcase classname="Login" name="Login Functionality" time="0.84123">
<system-out><![CDATA[Given User details..........................................................passed
When UI submits the User data...............................................passed
Then return Message user is authenticated...................................passed
]]></system-out>
</testcase>
</testsuite>
Below is output from cucumber.json
[
  {
    "id": "login",
    "description": "",
    "name": "Login",
    "keyword": "Feature",
    "line": 1,
    "elements": [
      {
        "id": "login;login-functionality",
        "tags": [
          {
            "name": "@smoke",
            "line": 3
          }
        ],
        "description": "",
        "name": "Login Functionality",
        "keyword": "Scenario",
        "line": 4,
        "steps": [
          {
            "result": {
              "duration": 841194605,
              "status": "passed"
            },
            "name": "User details",
            "keyword": "Given ",
            "line": 5,
            "match": {
              "location": "TestSuit.user_details()"
            }
          },
          {
            "result": {
              "duration": 17376,
              "status": "passed"
            },
            "name": "UI submits the User data",
            "keyword": "When ",
            "line": 6,
            "match": {
              "location": "TestSuit.ui_submits_the_User_data()"
            }
          },
          {
            "result": {
              "duration": 17850,
              "status": "passed"
            },
            "name": "return Message user is authenticated",
            "keyword": "Then ",
            "line": 7,
            "match": {
              "location": "TestSuit.return_Message_user_is_authenticated()"
            }
          }
        ],
        "type": "scenario"
      }
    ],
    "uri": "features/login.feature"
  }
]

How to check whether operating system is 64 bit or 32bit?

What is 32 and 64 bit operating system? The terms 32-bit and 64-bit refer to the way a computer's processor that is CPU, handles info...