OCJP REFERENCES

Java Packaging:

https://stackoverflow.com/questions/2193226/how-to-import-a-class-from-default-package

https://docs.oracle.com/javase/specs/#7.4.2

http://www.xyzws.com/javafaq/what-is-the-default-package/126

https://stackoverflow.com/questions/9729197/getting-current-class-name-including-package

https://coderanch.com/t/270542/certification/Package-statement-Import-statement

https://stackoverflow.com/questions/3179216/what-is-the-convention-for-word-separator-in-java-package-names?rq=1

https://stackoverflow.com/questions/6532726/java-package-politics?rq=1

https://www.intertech.com/Blog/whats-package-info-java-for/

https://stackoverflow.com/questions/12599058/eclipse-juno-what-is-the-use-of-package-info-java

https://www.leepoint.net/language/10basics/import.html

 

Imports in java:

http://www.studytonight.com/java/package-in-java.php

I have static import feature a lot while using unit testing and mocking libraries like Mockito, JUnit, TestNG and others. You can static import key class e.g.

import static org.junit.Assert.*
import static org.mockito.Mockito.*
import static org.mockito.Matcher.*

You can even configure Eclipse content assist to show statically imported method, without even them manually imported, by configuring them in favorites under content assist. Next time, if those libraries in your classpath, typing assert will show all assert methods from jUnit and so on.

Read more: http://javarevisited.blogspot.com/2012/10/what-is-static-import-in-java-5-example-tutorial.html#ixzz4wAxuGppM

https://stackoverflow.com/questions/29382728/constant-interface-anti-pattern-clarification

 

 

 

 

 

Advertisements

Order by , Group by in Java

This is one of the rare requirement like if you want sort some data and you wants to segregate the data by grouping some factor.

Here players are sorted by rank,remunation  and we are grouping them by gametype .

 
package com.java8.practice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

public class Collectors_reducing {
public static void main(String[] args) {
PersonPojo personPojo = new PersonPojo(1, "MESSI", 250f, "Football");
PersonPojo personPojo3 = new PersonPojo(3, "Ronaldhino", 150f, "Football");
PersonPojo personPojo2 = new PersonPojo(2, "Inesta", 100f, "Football");

PersonPojo personPojo4 = new PersonPojo(5, "Nadal", 140f, "Tennis");
PersonPojo personPojo5 = new PersonPojo(7, "Ivanovic", 55f, "Tennis");
PersonPojo personPojo6 = new PersonPojo(4, "Federer", 170f, "Tennis");

System.out.println("-------------Order By Rank, Group by GAMENAME-----------------------");

ArrayList arrayList = new ArrayList(
Arrays.asList(personPojo, personPojo2, personPojo3, personPojo4, personPojo6, personPojo5));
Comparator comparator = Comparator.comparing(PersonPojo::getPlayerRank);
Map<String, Optional> map = arrayList.stream().collect(
Collectors.groupingBy(PersonPojo::getGameName, Collectors.reducing(BinaryOperator.minBy(comparator))));
map.forEach((k,
v) -> System.out.println("---" + k + "----" + ((Optional) v).get().getPlayerName() + "---"
+ ((Optional) v).get().getPlayerRank() + "---"
+ +((Optional) v).get().getPlayerRemunation() + "---"
+ ((Optional) v).get().getGameName()));

System.out.println("---------------------------Order BY remunation, Group by GameName------------------");
Comparator comparator2 = Comparator.comparing(PersonPojo::getPlayerRemunation);
Map<String, Optional> map2 = arrayList.stream().collect(Collectors
.groupingBy(PersonPojo::getGameName, Collectors.reducing(BinaryOperator.minBy(comparator2))));

map2.forEach((k,
v) -> System.out.println("---" + k + "---" + ((Optional) v).get().getGameName() + "---"
+ ((Optional) v).get().getPlayerName() + "---"
+ ((Optional) v).get().getPlayerRank() + "---"
+ ((Optional) v).get().getPlayerRemunation()));

}
}

class PersonPojo {
private int playerRank;
private String playerName;
private float playerRemunation;
private String gameName;

public String getGameName() {
return gameName;
}

public void setGameName(String gameName) {
this.gameName = gameName;
}

public int getPlayerRank() {
return playerRank;
}

public void setPlayerRank(int playerRank) {
this.playerRank = playerRank;
}

public String getPlayerName() {
return playerName;
}

public void setPlayerName(String playerName) {
this.playerName = playerName;
}

public float getPlayerRemunation() {
return playerRemunation;
}

public void setPlayerRemunation(float playerRemunation) {
this.playerRemunation = playerRemunation;
}

public PersonPojo(int playerRank, String playerName, float playerRemunation, String gameName) {
this.playerRank = playerRank;
this.playerName = playerName;
this.playerRemunation = playerRemunation;
this.gameName = gameName;
}

@Override
public String toString() {
return "PersonPojo [playerRank=" + playerRank + ", playerName=" + playerName + ", playerRemunation="
+ playerRemunation + ", gameName=" + gameName + "]";
}

}

output:

————-Order By Rank, Group by GAMENAME———————–
—Tennis—-Federer—4—170.0—Tennis
—Football—-MESSI—1—250.0—Football
—————————Order BY remunation, Group by GameName——————
—Tennis—Tennis—Ivanovic—7—55.0
—Football—Football—Inesta—2—100.0
Picked up _JAVA_OPTIONS: -Xmx512M

sort by id , name -custom sorting

Student.java:

package com.me.pack;

import java.util.Comparator;

@SuppressWarnings(“rawtypes”)
public class Student implements Comparable {
private int id;
private String name;
private float sal;

public static final Comparator idComparator = new Comparator() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.id – o2.id;
}
};

public static final Comparator nameComparator = new Comparator() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.name.compareTo(o2.name);
}
};

public static final Comparator salComparator = new Comparator() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return (int) (o1.sal – o2.sal);
}
};

public static final Comparator comp=
(Student s1, Student s2) -> s1.getName().compareTo(s2.getName());

@Override
public int compareTo(Student arg0) {
// TODO Auto-generated method stub
return this.id – arg0.id;
}

public int getId() {
return id;
}

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

public String getName() {
return name;
}

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

public float getSal() {
return sal;
}

public void setSal(float sal) {
this.sal = sal;
}

public Student(int id, String name, float sal) {
super();
this.id = id;
this.name = name;
this.sal = sal;
}

@Override
public String toString() {
return “Student [id=” + id + “, name=” + name + “, sal=” + sal + “]”;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Float.floatToIntBits(sal);
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Float.floatToIntBits(sal) != Float.floatToIntBits(other.sal))
return false;
return true;
}

}

 

Test.java:

package com.me.pack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorStudentLamda {
public static void main(String[] args) {
Student student = new Student(125, “bcv”, 546.09f);
Student student2 = new Student(123, “mno”, 123.09f);
Student student3 = new Student(130, “fgh”, 74357.09f);

List list = new ArrayList(Arrays.asList(student, student2, student3));
for (Student studenttemp : list) {
System.out.println(studenttemp);
}
System.out.println(“—————–“);
Collections.sort(list, Student.idComparator);
for (Student studentR : list) {
System.out.println(studentR);
}
System.out.println(“—————–“);
Collections.sort(list, Student.nameComparator);
for (Student studentR : list) {
System.out.println(studentR);
}
System.out.println(“—————–“);
Collections.sort(list, Student.salComparator);
for (Student studentR : list) {
System.out.println(studentR);
}
System.out.println(“—————–“);
Collections.sort(list, Student.comp);
for (Student studentR : list) {
System.out.println(studentR);
}
}
}

 

 

Invoke from java8:
Collections.sort(list, Student.comp);
for (Student studentR : list) {
System.out.println(studentR);
}

 

output:

Student [id=125, name=bcv, sal=546.09]
Student [id=123, name=mno, sal=123.09]
Student [id=130, name=fgh, sal=74357.09]
—————–
Student [id=123, name=mno, sal=123.09]
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
—————–
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
Student [id=123, name=mno, sal=123.09]
—————–
Student [id=123, name=mno, sal=123.09]
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
—————–
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
Student [id=123, name=mno, sal=123.09]
Picked up _JAVA_OPTIONS: -Xmx512M

refer : http://www.concretepage.com/java/jdk-8/lambda-expressions-java-8-examplehttp://www.concretepage.com/java/jdk-8/lambda-expressions-java-8-
example

http://javarevisited.blogspot.in/2014/01/java-comparator-example-for-custom.html

Java-8 Predicates

You can get plenty good enough points here:

https://www.javabrahman.com/java-8/java-8-java-util-function-predicate-tutorial-with-examples

 

 

package com.me.pack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Java8PredicateTest2 {
public static void main(String[] args) {
Predicate predicate= even -> even%2==0;
List integers =new ArrayList(Arrays.asList(123,120,151,186,124));
List integersEven= filterList(integers,predicate);
integersEven.forEach(System.out::println);
}

private static List filterList(List integers, Predicate predicate) {
// TODO Auto-generated method stub
List integerstemp=new ArrayList();
for(Integer integer:integers){
if(predicate.test(integer)){
integerstemp.add(integer);
}
}
return integerstemp;
}
}

 

output:
120
186
124
Picked up _JAVA_OPTIONS: -Xmx512M

 

package com.me.pack;

import java.util.function.Function;
import java.util.function.Predicate;

public class Java8PredicateTest {
public static void main(String[] args) {
Predicate male =
h -> h.getName().equals(“madhu”) && “male”.equals(h.getGender());
Predicate female =
h -> h.getName().equals(“ammu”) && “female”.equals(h.getGender());

Function maleStyle =
s -> “Hi, You are male and age ” + s.getName();

Function femaleStyle =
s -> “Hi, You are female and age ” + s.getName();

HumanBeing s1 = new HumanBeing(“madhu”, “male”);
if (male.test(s1)) {
System.out.println(s1.predicateCustomFun(maleStyle));
} else if (female.test(s1)) {
System.out.println(s1.predicateCustomFun(femaleStyle));
}
}
}

 

package com.me.pack;

import java.util.function.Function;

public class HumanBeing {
private String name;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public HumanBeing(String name, String gender) {
super();
this.name = name;
this.gender = gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String predicateCustomFun(Function maleStyle){
return maleStyle.apply(this);
}
}

 

output:
Picked up _JAVA_OPTIONS: -Xmx512M
Hi, You are male and age madhu

Java -8 stream package

package com.java8.practice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class AllAnyNoneExample {
public static void main(String[] args) {
Predicate predicate = n -> n % 2 == 0;
List integers = Arrays.asList(102, 23, 45, 63, 90, 64, 23, 45);

// allmatch anymatch nonematch
System.out.println(integers.stream().allMatch(predicate));
System.out.println(integers.stream().anyMatch(predicate));
System.out.println(integers.stream().noneMatch(predicate));

// collect
List strings = new ArrayList(Arrays.asList("bcd", "cdf", "hdsbhjds", "hdfc"));
String op = strings.stream().collect(Collectors.joining("--"));
System.out.println(op);

// concat
List stringsIn1 = new ArrayList(Arrays.asList("icici", "hdfc"));
List stringsIn2 = new ArrayList(Arrays.asList("sbi", "kotak"));
Stream opConcat = Stream.concat(stringsIn1.stream(), stringsIn2.stream());
opConcat.forEach(s -> System.out.println(s));

// count
long l = integers.stream().count();
System.out.println(l);

// distinct
long l2 = integers.stream().distinct().count();
System.out.println(l2);

// predicate and filter
Predicate predicate2 = s -> s % 10 == 0;
integers.stream().filter(predicate2).forEach(s -> System.out.println(s));

// finAny and finaLast findFirst
String string = strings.stream().findAny().get();
System.out.println(string);

// flatMap
Integer[][] intDArray = { { 3, 24 }, { 3, 4 }, { 5, 6 } };
Arrays.stream(intDArray).flatMap(row -> Arrays.stream(row)).filter(n -> n % 2 == 0)
.forEach(s -> System.out.println(s + "---"));

Arrays.stream(intDArray).flatMap(row -> Arrays.stream(row)).filter(n -> n % 3 == 0)
.forEach(s -> System.out.println(s));

// forEach and forEachOrdered
Integer[] integersList = { 12, 34, 98, 212, 456, 234, 658, 213, 3543, 54654, 6, 43 };
Arrays.stream(integersList).filter(num -> num % 2 == 0).forEach(s -> System.out.print("--" + s));
Arrays.stream(integersList).filter(num -> num % 2 == 0).forEachOrdered(s -> System.out.print("--" + s));

// generate and limit
Stream.generate(Math::random).limit(10).forEach(s -> System.out.print(s));

// iterate
Stream stream = Stream.iterate(1, n -> n * 2).limit(5);
stream.forEach(s -> System.out.print(s + " "));

// map()
List list = Arrays.asList(1, 2, 3, 4);
list.stream().map(num -> num * 2).forEach(s -> System.out.println("__-" + s));

List listMinMax = new ArrayList(Arrays.asList("G", "B", "M", "O", "P", "s"));
String max = listMinMax.stream().max(Comparator.comparing(String::valueOf)).get();
String min = listMinMax.stream().min(Comparator.comparing(String::valueOf)).get();
System.out.println(max + "--" + min);

// peek
listMinMax.stream().peek(s -> System.out.println(s + "ABAP")).collect(Collectors.toList());

// reduce
int[] reduceArray = { 2, 6, 9, 25, 46 };
int sum = Arrays.stream(reduceArray).reduce(0, (x, y) -> (x + y));
System.out.println(sum);

// skip
int[] aSkip = { 12, 34, 52, 16, 66 };
Arrays.stream(aSkip).skip(3).forEach(s -> System.out.println(s + "---"));

// sorted
Map mapValues = new HashMap();
mapValues.put("no1", "123");
mapValues.put("no10", "hgf");
mapValues.put("mky", "sadfsa");
mapValues.put("tre", "34532");
mapValues.put("gds", "gg5y");
mapValues.put("sdfds", "sdfds");

// sorting based on key
mapValues.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
.forEach(s -> System.out.println(s.getValue() + "---" + s.getKey()));

// sorting based on value
mapValues.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
.forEach(s -> System.out.println(s.getValue() + "---" + s.getKey()));

String[] stringsNames = new String[]{"dfg","mno","cfx"};
Object[] obj = Stream.of(stringsNames).toArray();
for(Object object:obj){
System.out.println("---"+object);
}

}
}

false
true
false
bcd–cdf–hdsbhjds–hdfc
icici
hdfc
sbi
kotak
8
6
90
bcd
24—
4—
6—
3
24
3
6
–12–34–98–212–456–234–658–54654–6–12–34–98–212–456–234–658–54654–60.90594481675002210.81813738818315030.50438793979534930.58841494828841320.229276714851393230.053862502898993080.73554686557288540.46758853420518830.095253156593703040.67151235875973671 2 4 8 16 __-2
__-4
__-6
__-8
s–B
GABAP
BABAP
MABAP
OABAP
PABAP
sABAP
88
16—
66—
gg5y—gds
sadfsa—mky
123—no1
hgf—no10
sdfds—sdfds
34532—tre
123—no1
34532—tre
gg5y—gds
hgf—no10
sadfsa—mky
sdfds—sdfds
—dfg
—mno
—cfx
Picked up _JAVA_OPTIONS: -Xmx512M

JAVA-8 Features

Default method in Interface

Why we need default method in interface.

  • In general Interface is a collection of un-implemented methods i.e only abstract methods.Rules before java-8 are
  • //All methods are default abstract methods.
  • Any variable should be final and static.
  • It is not instansable i.e Interface doesn’t have any constructor.
  • Example : List Interface _https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html

package com.me.pack;

public interface SampleInterface {

static final int value=1;
abstract void method1(int a);
String method2();
}

  • If you wants to implement the interface then you should implement all its methods as below.

package com.me.pack;package com.me.pack;
public interface SampleInterface { static final int num = 10; static final String name = “John”;
abstract void method1(int a);
String method2();}
class SampleClass implements SampleInterface {
@Override public void method1(int a) { // TODO Auto-generated method stub System.out.println(SampleClass.num * a); }
@Override public String method2() { // TODO Auto-generated method stub return SampleClass.name; }
}

Why we need default method ?

Suppose if there is a Bank(I) which provides facilities to their customers by two ways i.e Customerservice(C)/Netbanking(C).Due to advancement bank about to provide a new way to reach out their customers through mobile banking then Then remaining two implemtors i.e Customerservice and Netbanking has to implement(avail) the new features so again we have to do lots code change.

Similarly default static method will works as a helper method.

Example:


package com.me.pack;

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

}
}

interface Bank {
default void mobileBanking() {
System.out.println(“Most people will do -1”);
}

default void virtualBanking() {
System.out.println(“less people will do -2”);
}

void customerService();

void netBanking();
}

interface Insurance {
static int getTheValue() {
return 123;
}

default void virtualBanking() {
System.out.println(“less people will do -2”);
}

void customerService();

void netBanking();
}

class HDFCBank implements Bank {

@Override
public void customerService() {
// TODO Auto-generated method stub
}

@Override
public void netBanking() {
// TODO Auto-generated method stub

}

}

class LibertyInsureur implements Insurance {

@Override
public void customerService() {
// TODO Auto-generated method stub

}

@Override
public void netBanking() {
// TODO Auto-generated method stub

}

}

class CombinerClass implements Insurance, Bank {

@Override
public void customerService() {
// TODO Auto-generated method stub

}

@Override
public void netBanking() {
// TODO Auto-generated method stub

}

// Has to implement this method
@Override
public void virtualBanking() {
// TODO Auto-generated method stub
Insurance.super.virtualBanking();
}

}


public class DefaultMethodsJava8 {
public static void main(String[] args) {
HDFCBank hdfcBank=new HDFCBank();
hdfcBank.customerService();
hdfcBank.netBanking();

//Any new implementaions can place here
hdfcBank.virtualBanking();
hdfcBank.mobileBanking();

Insurance insurance=new LibertyInsureur();
insurance.customerService();
insurance.netBanking();

//new features
insurance.virtualBanking();
//helper method
((LibertyInsureur) insurance).getHere();
Insurance.getTheValue();

CombinerClass combinerClass=new CombinerClass();
//Common has to implemt
combinerClass.virtualBanking();
}
}

 

Hidden features of JAVA-7

Here are some stuff  that I came across so far.

 1.NumberFormatException
int value = 123_8934758;
System.out.println(value);

2.String as argument in Switch condition.

String key1 = "HYD", key2 = "BLR";

Scanner scanner = new Scanner(new InputStreamReader(System.in));
String input = scanner.nextLine();

switch (input) {
case key1:
System.out.println("HYD HERE");
break;
case key1:
System.out.println("BLR HERE");
break;

default:
System.out.println("DEFAULT HERE");
break;
}

3. Diamond operator
When we doesn’t place both sides then no issues and it accepts specified any
type of object like Integer,String,Object etc because by default it will take
Object as generic type.

When we doesn’t place at left side then no issues and it accepts specified any
type of object like Integer,String,Object etc because by default it will take
Object as generic type.

When we place both sides then no issues and it accepts only specified Generic type.

When we place at left side then issues and it accepts only specified any type.

List list = new ArrayList();
List list2 = new ArrayList();
List list3 = new ArrayList();
List list4 = new ArrayList();

List list5 = new ArrayList();
List list6 = new ArrayList();

list5.add(new Long(123));
list5.add(new Integer(548));

list.add("ABC");
list.add(new Object());
list.add(new String("Hey"));
list.add(new Integer(125));

list2.add(new Object());
list2.add(new String("Hey"));
list2.add(new Integer(125));

list3.add(new Object());
list3.add(new String("Hey"));
list3.add(new Integer(125));

list4.add(new Object());
list4.add(new String("Hey"));
list4.add(new Integer(125));

4. Parallel catching of Exceptions:

When all are placed in different exception hierarchies then we can place as this.
NullPointerException | IOException | ArithmeticException | IndexOutOfBoundsException ex

If they fall under same hierarchy then use the base Exception. The below will gives you the CE.

catch (NullPointerException | IOException | ArithmeticException | FileNotFoundException ex) {
ex.printStackTrace();
}

If you are using Checked Exception then it should be thrown.
IOException etc.

try {
File file = new File("C://Demos//me.txt");
FileInputStream fileInputStream = new FileInputStream(file);

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
while (bufferedReader.readLine() != null) {
System.out.println(new SimpleDateFormat("DD/MM/YYYY"));
}
throw new ArithmeticException();
} catch (NullPointerException | IOException | ArithmeticException | IndexOutOfBoundsException ex) {
ex.printStackTrace();
}

5. Try with resource
Internally it uses implements AutoCloseable {

@Override
public void close() throws Exception {
// TODO Auto-generated method stub
System.out.println(“hey java-7 closable”);
}

try (BufferedReader bufferedReader = new BufferedReader(
new FileReader("C:\\Users\\n0290635\\Desktop\\het.txt"))) {
while (bufferedReader.readLine() != null) {
System.out.println(bufferedReader.readLine());
}
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}

try (CustomClass customClass = new CustomClass()) {
customClass.methodNene(123);
} catch (Exception exception) {
exception.printStackTrace();
}

class CustomClass implements AutoCloseable {

@Override
public void close() throws Exception {
// TODO Auto-generated method stub
System.out.println("hey java-7 closable");
}

public void methodNene(int a) {
System.out.println("result:" + a * a * 120);
}

}

6. Rethrow error -Throwing the exception in catch block too.
private static void rethrowErrorJAVA7() throws IOException, Exception {

try {
new SimpleDateFormat("yyyyMMdd").parse("foo");
new FileReader("file.txt").read();
} catch (ArithmeticException arithmeticException) {

} catch (Exception exception) {
throw exception;
}
}

Types of layouts in Log4j

There are numerous Layouts in log4j.

Refer Here : https://logging.apache.org/log4j/2.0/manual/layouts.html

Sample log4j.properties

# Root logger option
log4j.rootLogger=TRACE,stdout,file,filehtml,filexml,filejson
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n - %t - %r -%M
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=V:/logs/user_timings.log
log4j.appender.file.MaxFileSize=10KB
log4j.appender.file.MaxBackupIndex=3
log4j.appender.file.layout= org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%
# Redirect log messages to a log file, support file rolling.
log4j.appender.filehtml=org.apache.log4j.RollingFileAppender
log4j.appender.filehtml.File=V:/logs/user_timings_html.html
log4j.appender.filehtml.MaxFileSize=10KB
log4j.appender.filehtml.MaxBackupIndex=3
log4j.appender.filehtml.layout= org.apache.log4j.HTMLLayout
log4j.appender.filehtml.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.filexml=org.apache.log4j.RollingFileAppender
log4j.appender.filexml.File=V:/logs/user_timings_xml.xml
log4j.appender.filexml.MaxFileSize=10KB
log4j.appender.filexml.MaxBackupIndex=3
log4j.appender.filexml.layout= org.apache.log4j.xml.XMLLayout
log4j.appender.filexml.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.filejson=org.apache.log4j.RollingFileAppender
log4j.appender.filejson.File=V:/logs/user_timings_json.json
log4j.appender.filejson.MaxFileSize=10KB
log4j.appender.filejson.MaxBackupIndex=3
log4j.appender.filejson.layout= org.apache.log4j.xml.JSONLayout
log4j.appender.filejson.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

 

output:

Untitled.png

HttpSessionListener(C) – Get user creation Time/LastLogin Time/ Login Duration/Maintain a log of newly created users.

This is one of the common requirements in kinda security projects.

Refer Here: http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpSessionListener.html

MySessionListener.java :

package com.me.pack;

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;

public class MySessionListener implements HttpSessionListener {
Logger logger = Logger.getLogger(LoginServlet.class);

@Override
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
logger.debug(” Listener Session Created” + arg0.getSession().getId());
logger.info(“Listener Session Created” + arg0.getSession().getCreationTime());
}

@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
logger.info(“Listener Session Destroyed”);
}

}
LoginServlet.java :

package com.me.pack;

import java.io.IOException;

import java.text.SimpleDateFormat;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

public class LoginServlet extends HttpServlet {
Logger logger = Logger.getLogger(LoginServlet.class);

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub

HttpSession httpSession = req.getSession(false);
;
RequestDispatcher requestDispatcher = null;

String userName = req.getParameter(“username”);
String password = req.getParameter(“password”);
logger.info(“Username: ” + userName);
logger.info(“Password: ” + password);

if (userName != null && password != null) {
try {
if (httpSession == null) {
// Not created yet. Now do so yourself.
httpSession = req.getSession();
} else {
// Already created.
}
} catch (Exception exception) {
logger.error(“session duplicate”, exception);
requestDispatcher = req.getRequestDispatcher(“welcomeses.jsp”);
}
String S = new SimpleDateFormat(“MM/dd/yyyy HH:mm:ss”).format(httpSession.getCreationTime());
logger.info(“Session ID ” + httpSession.getId());
httpSession.setAttribute(“logintime”, S);
httpSession.setAttribute(“username”, userName);
httpSession.setAttribute(“password”, password);
logger.info(“Session Username: ” + httpSession.getAttribute(“username”));
requestDispatcher = req.getRequestDispatcher(“welcome.jsp”);
} else {
requestDispatcher = req.getRequestDispatcher(“failure.jsp”);
}
requestDispatcher.forward(req, resp);
}
}

 

LogoutServlet.java :
package com.me.pack;

import java.io.IOException;
import java.text.SimpleDateFormat;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

public class LogoutServlet extends HttpServlet {
Logger logger = Logger.getLogger(LoginServlet.class);

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
logger.debug(“logout”);
HttpSession httpSession = req.getSession();
System.out.println(httpSession.getLastAccessedTime());
String string = new SimpleDateFormat(“MM/dd/yyyy HH:mm:ss”).format(httpSession.getLastAccessedTime());
logger.info(“Session ID: ” + httpSession.getId());
logger.info(“Session Logout time:” + string);
String sec = (String) httpSession.getAttribute(“logintime”);
httpSession.invalidate();

// HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat(“MM/dd/yyyy HH:mm:ss”);

java.util.Date d1 = null;
java.util.Date d2 = null;

try {
d1 = (java.util.Date) format.parse(sec);
d2 = format.parse(string);

// in milliseconds
long diff = d2.getTime() – d1.getTime();

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);

logger.info(diffDays + ” days, “);
logger.info(diffHours + ” hours, “);
logger.info(diffMinutes + ” minutes, “);
logger.info(diffSeconds + ” seconds.”);

} catch (Exception e) {
logger.error(“Conversion Data”, e);
e.printStackTrace();
}

}
}

login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
Insert title here

UserName :
Password :
 

welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"Insert title hereWELCOME .... ${sessionScope['username']}

 

failure.jsp

Insert title here

Ooops………Invalid!

lo4j.properties

# Root logger option
log4j.rootLogger=TRACE,stdout,file
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L – %m%n – %t – %r -%M
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=V:/logs/user_timings.log
log4j.appender.file.MaxFileSize=10KB
log4j.appender.file.MaxBackupIndex=3
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L – %m%n

Output:

Sep 05, 2017 1:32:02 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.8.0_111\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_111/bin/client;C:/Program Files/Java/jre1.8.0_111/bin;C:/Program Files/Java/jre1.8.0_111/lib/i386;C:\Perl\site\bin;C:\Perl\bin;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\BMC Software\BladeLogic\8.6\NSH\bin;C:\Program Files\Java\jdk1.8.0_111\bin;C:\Program Files\Citrix\System32\;C:\Program Files\Citrix\ICAService\;C:\Users\n0290635\Desktop\Sunday\apache-ant-1.9.9bin;C:\Program Files\TortoiseSVN\bin;C:\Program Files\CVSNT;.C:\Program Files\Java\jdk1.8.0_111\bin;.C:\Program Files\BMC Software\BladeLogic\8.6\NSH\bin;C:\Perl\bin\perl.exe;C:\New folder\eclipse;;.
Sep 05, 2017 1:32:02 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:Session_Listener’ did not find a matching property.
Sep 05, 2017 1:32:03 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler [“http-bio-8080”]
Sep 05, 2017 1:32:03 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler [“ajp-bio-8009”]
Sep 05, 2017 1:32:03 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2097 ms
Sep 05, 2017 1:32:03 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Sep 05, 2017 1:32:03 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.42
Sep 05, 2017 1:32:04 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [450] milliseconds.
Sep 05, 2017 1:32:05 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler [“http-bio-8080”]
Sep 05, 2017 1:32:05 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler [“ajp-bio-8009”]
Sep 05, 2017 1:32:05 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1454 ms
2017-09-05 13:32:07 DEBUG LoginServlet:15 – Listener Session Created70C936BBC0863796F6C783E2B2FF5AB2
– http-bio-8080-exec-3 – 1 -sessionCreated2017-09-05 13:32:07 INFO LoginServlet:16 – Listener Session Created1504632727519
– http-bio-8080-exec-3 – 6 -sessionCreated2017-09-05 13:32:34 DEBUG LoginServlet:15 – Listener Session CreatedA7FD51C8DDF38541B734F5E52D32144F
– http-bio-8080-exec-5 – 26978 -sessionCreated2017-09-05 13:32:34 INFO LoginServlet:16 – Listener Session Created1504632754521
– http-bio-8080-exec-5 – 26979 -sessionCreated2017-09-05 13:32:55 INFO LoginServlet:29 – Username: Navee
– http-bio-8080-exec-7 – 47900 -doPost2017-09-05 13:32:55 INFO LoginServlet:30 – Password: Hello@123
– http-bio-8080-exec-7 – 47901 -doPost2017-09-05 13:32:55 INFO LoginServlet:45 – Session ID A7FD51C8DDF38541B734F5E52D32144F
– http-bio-8080-exec-7 – 47902 -doPost2017-09-05 13:32:55 INFO LoginServlet:49 – Session Username: Navee
– http-bio-8080-exec-7 – 47903 -doPost2017-09-05 13:33:04 DEBUG LoginServlet:15 – Listener Session CreatedEF78A44116F4413A33708FBFF3D036B1
– http-bio-8080-exec-9 – 57087 -sessionCreated2017-09-05 13:33:04 INFO LoginServlet:16 – Listener Session Created1504632784630
– http-bio-8080-exec-9 – 57088 -sessionCreated2017-09-05 13:33:17 INFO LoginServlet:29 – Username: Lohitha
– http-bio-8080-exec-3 – 69810 -doPost2017-09-05 13:33:17 INFO LoginServlet:30 – Password: Hello@124
– http-bio-8080-exec-3 – 69810 -doPost2017-09-05 13:33:17 INFO LoginServlet:45 – Session ID EF78A44116F4413A33708FBFF3D036B1
– http-bio-8080-exec-3 – 69810 -doPost2017-09-05 13:33:17 INFO LoginServlet:49 – Session Username: Lohitha
– http-bio-8080-exec-3 – 69810 -doPost2017-09-05 13:33:40 INFO LoginServlet:29 – Username: Prasanna
– http-bio-8080-exec-4 – 92460 -doPost2017-09-05 13:33:40 INFO LoginServlet:30 – Password: Hello@125
– http-bio-8080-exec-4 – 92460 -doPost2017-09-05 13:33:40 INFO LoginServlet:45 – Session ID 70C936BBC0863796F6C783E2B2FF5AB2
– http-bio-8080-exec-4 – 92460 -doPost2017-09-05 13:33:40 INFO LoginServlet:49 – Session Username: Prasanna
– http-bio-8080-exec-4 – 92460 -doPost2017-09-05 13:33:45 DEBUG LoginServlet:27 – logout
– http-bio-8080-exec-6 – 98374 -doPost1504632777867
2017-09-05 13:33:45 INFO LoginServlet:31 – Session ID: A7FD51C8DDF38541B734F5E52D32144F
– http-bio-8080-exec-6 – 98374 -doPost2017-09-05 13:33:45 INFO LoginServlet:32 – Session Logout time:09/05/2017 13:32:57
– http-bio-8080-exec-6 – 98374 -doPost2017-09-05 13:33:45 INFO LoginServlet:22 – Listener Session Destroyed
– http-bio-8080-exec-6 – 98374 -sessionDestroyed2017-09-05 13:33:45 INFO LoginServlet:54 – 0 days,
– http-bio-8080-exec-6 – 98374 doPost2017-09-05 13:33:45 INFO LoginServlet:55 – 0 hours,
– http-bio-8080-exec-6 – 98374 -doPost2017-09-05 13:33:45 INFO LoginServlet:56 – 0 minutes,
– http-bio-8080-exec-6 – 98374 -doPost2017-09-05 13:33:45 INFO LoginServlet:57 – 23 seconds.
– http-bio-8080-exec-6 – 98374 -doPost2017-09-05 13:33:56 DEBUG LoginServlet:27 – logout
– http-bio-8080-exec-4 – 108470 -doPost1504632820003
2017-09-05 13:33:56 INFO LoginServlet:31 – Session ID: 70C936BBC0863796F6C783E2B2FF5AB2
– http-bio-8080-exec-4 – 108470 -doPost2017-09-05 13:33:56 INFO LoginServlet:32 – Session Logout time:09/05/2017 13:33:40
– http-bio-8080-exec-4 – 108470 -doPost2017-09-05 13:33:56 INFO LoginServlet:22 – Listener Session Destroyed
– http-bio-8080-exec-4 – 108470 -sessionDestroyed2017-09-05 13:33:56 INFO LoginServlet:54 – 0 days,
– http-bio-8080-exec-4 – 108470 -doPost2017-09-05 13:33:56 INFO LoginServlet:55 – 0 hours,
– http-bio-8080-exec-4 – 108470 -doPost2017-09-05 13:33:56 INFO LoginServlet:56 – 1 minutes,
– http-bio-8080-exec-4 – 108470 -doPost2017-09-05 13:33:56 INFO LoginServlet:57 – 33 seconds.
– http-bio-8080-exec-4 – 108470 -doPost2017-09-05 13:34:01 DEBUG LoginServlet:27 – logout
– http-bio-8080-exec-9 – 114044 -doPost1504632797353
2017-09-05 13:34:01 INFO LoginServlet:31 – Session ID: EF78A44116F4413A33708FBFF3D036B1
– http-bio-8080-exec-9 – 114045 -doPost2017-09-05 13:34:01 INFO LoginServlet:32 – Session Logout time:09/05/2017 13:33:17
– http-bio-8080-exec-9 – 114046 -doPost2017-09-05 13:34:01 INFO LoginServlet:22 – Listener Session Destroyed
– http-bio-8080-exec-9 – 114046 -sessionDestroyed2017-09-05 13:34:01 INFO LoginServlet:54 – 0 days,
– http-bio-8080-exec-9 – 114047 -doPost2017-09-05 13:34:01 INFO LoginServlet:55 – 0 hours,
– http-bio-8080-exec-9 – 114047 -doPost2017-09-05 13:34:01 INFO LoginServlet:56 – 0 minutes,
– http-bio-8080-exec-9 – 114048 -doPost2017-09-05 13:34:01 INFO LoginServlet:57 – 13 seconds.
– http-bio-8080-exec-9 – 114049 -doPost

web.xml:

Session_Listener

login.jsp

com.me.pack.MySessionListener
LoginServlet
com.me.pack.LoginServlet

LoginServlet
/LoginServlet

LogoutServlet
com.me.pack.LogoutServlet

LogoutServlet
/LogoutServlet

 

Untitled.png