0% found this document useful (0 votes)
51 views49 pages

Learning Java: in II Days

The document outlines a 2-day Java training course, covering basic Java programming concepts like classes, objects, access modifiers, encapsulation, inheritance, polymorphism, and abstract and interface classes. It includes examples and explanations of each topic, with the goal of helping students understand OOP principles and be able to write basic Java code after completing the course.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views49 pages

Learning Java: in II Days

The document outlines a 2-day Java training course, covering basic Java programming concepts like classes, objects, access modifiers, encapsulation, inheritance, polymorphism, and abstract and interface classes. It includes examples and explanations of each topic, with the goal of helping students understand OOP principles and be able to write basic Java code after completing the course.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Learning Java

in II days
Training Course Out-Line

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

Prerequisites

Tools
Application Server
Sun Java Glassfish v2.1.1
Database
MySql version 5
IDE
NetBeans IDE 6.8 (Sun Micro System corp.)
Other
Java SDK 1.6
Jconnector

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

Basic Java Programming

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1. Java Programming Concepts

Java
modifiers
OOP
Operators, Variable Types, Control Flow Statements
(Exception Handler)
section

Basic Java Programming
Java

1.1. Class and Object

Java (Object Oriented Programming)


class Data Method
Example 1.1
public class Dog {
private String species;
// constructor
public Dog(String species) {
this.species = species;
}

public String bark() {


return bog bog;
}

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

object methods
public class TestDog {
public static void main(String args[]) {
// create new object
Dog mydog = new Dog(bangkaew);

// bark
System.out.println(mydog.bark());

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.2. Access Modifier in Java

Java OOP class, method


data
public class package
private class
protected class ( inheritance ) class

Access Modifier

Same Class

Same Package

Subclass

Other packages

public

protected

Not define

private

Figure 1.Access Modifiers

class Dog {
private String species;
// data_member color protected
protected String color;
// constructor
public Dog(String species) {
this.species = species;
}
public String bark() {
return bog bog;
}
// method color
public String getColor() {
return color;
}

// method color
public void setColor(String color) {
this.color = color;
}

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.3. Encapsulation, Inheritance and Polymorphism

1.3.1. Encapsulation

Encapsulation class class



public, protected private 1.2
Access Modifiers

1.3.2. Inheritance


extends
Example
public class SuperDog extends Dog {

// methods
public void speak(String message) {
System.out.println(The SuperDog speaks + message);
}

Object

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.3.3. Polymorphism

Overloaded Methods

public class SuperDog extends Dog {


public void speak(String message) {
System.out.println(The SuperDog speaks +
message);
}

// Overloaded methods
public void speak(String message, int count) {
for (int i=0 ; i<count ; i++) {
System.out.println(The SuperDog speaks +
message);
}
}

Overridden Methods

public class SuperDog extends Dog {


// object
public void bark() {
return I am SuperDog, bog bog.;
}
}

Dynamic Methods Binding

Java
runtime

class ThaiSuperDog extends SuperDog {


public String bark() {
return sawaddee;
}
}
class UsaSuperDog extends SuperDog {

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

public String bark() {


return hello;
}

class FranceSuperDog extends SuperDog {


public String bark() {
return bnojour;
}
}
public class TestDynamicBinding
{
public static void main(String args[]) {
Dog ref;
// set up var for a dog
ThaiSuperDog tdog = new ThaiSuperDog("bangkeaw);
UsaSuperDog udog = new UsaSuperDog("bulldog");
FranceSuperDog fdog = new FranceSuperDog("hounds");

// now reference each as a


ref = tdog; ref.bark(); //
ref = udog; ref.bark(); //
ref = fdog; ref.bark(); //

dog
sawaddee
hello
bnojour

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.4. Abstract & Interface Class


1.4.1. Abstract Class

methods implement abstract


methods (predefine ) implement
implement
Example
public abstract class Animal {
private String name;
// constructor
public Animal(String name) {
this.name = name;
}
public String getName() {
return (name);
}
}

public abstract void speak(); // implement

1.4.2. Interface Class

Interfaces methods
Example
public interface Working
{
public void work();
}

work() implement
interface class implements .
Example
public class WorkingDog extends Dog implements Working {
public WorkingDog(String species) {
super(species);
// use parent constructor
}

// implement interface method


public void work() {
speak();
System.out.println("I can herd sheep and cows");
}

10

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.4.3. Abstract Interface Class?

internet

Abstract Interface

Abstract Interface
( extends implements )
?

Posted 24 August 2010 - 08:14 PM

Interface java
code
java code
Abstract class
extend abstract class code

Posted 24 August 2010 - 10:42 PM

abstract class method method abstract method


method class class class
implement abstract class class
method class abstract code
method class code class class

abstract
class abstract method class
class implement method

interface class multiple inheritance class 1 class


implement interface 1 interface ( interface implement method

class method signature )


interface class design principle coding to interface,
not implementation class. code class dependency
class class
class Fighter {
string Fight(Fighter enemy) { ... }
}
class Tournament {
void Fight(Fighter a, Fighter B) {
a.Fight(B);
}
}

11

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

code Fighter (fight) Tournament class Fighter


class Tournament Fighter dependency 2 class
interface code

interface IBoxing {
string Fight(IBoxing enemy);
}
class Fighter implements IBoxing {
string Fight(IBoxing enemy) { ... } // implement iboxing
}
class Tounament {
void Fight(IBoxing a, IBoxing B) { // parameter interface type
a.Fight(B);
}
}

class Tournament parameter fighter


object implement interface IBoxing

class implement interface 1 class


dynamic

class code class Fighter class class


code Fight
Fight() implement code method fight() class
pass object class method Fight() Tournament method Tournament.Fight()
object 1 class code
implement class
code Tournament

Fighter Boxing implement


interface 2 Fighter
multiple inheritance

12

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.5. Constants

constants

keyword final
data, method class
1.5.1) Final classes

final class class


public final class MyFinalClass {...}
1.5.2)

Final methods

Methods final overridden*


public class MyClass {
public final void myFinalMethod() {...}
}

* overridden method parameters method

1.5.3) Final variables


public class MyClass {
public final double PI = 3.141592653589793;
[...]
}

13

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.6. Static

keyword static (variable) method


Static variables

static
object class
static instance object
instance
public class MyClass {
static int number;
[...]
}

Static methods

Method static method


static methods
public class MyClass {
static int myStaticMethod() {...}
}
object
int ret = MyClass.myStaticMethod();

14

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.7. comment

code 2

single line comment

//
public class MyClass {
static int myStaticMethod() {
//
int x = 10; //
}
}

multi line comment

/* */
public class MyClass {
/**
*
* 2
*/
static int myStaticMethod() {...}
}

15

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.8) Operators
Summary of Operators
The following quick reference summarizes the operators supported by
the Java programming language.
Simple Assignment Operator
=

Simple assignment operator

Arithmetic Operators
+
*
/
%

Additive operator (also used for String concatenation)


Subtraction operator
Multiplication operator
Division operator
Remainder operator

Unary Operators
+
Unary plus operator; indicates positive value (numbers are
positive without this, however)
Unary minus operator; negates an expression
++
Increment operator; increments a value by 1
-Decrement operator; decrements a value by 1
!
Logical compliment operator; inverts the value of a boolean
Equality and Relational Operators
==
!=
>
>=
<
<=

Equal to
Not equal to
Greater than
Greater than or equal to
Less than
Less than or equal to

Conditional Operators
&&
||
?:

Conditional-AND
Conditional-OR
Ternary (shorthand for if-then-else statement)

Type Comparison Operator


instanceof

Compares an object to a specified type

Bitwise and Bit Shift Operators


~
<<
>>
>>>
&
^
|

Unary bitwise complement


Signed left shift
Signed right shift
Unsigned right shift
Bitwise AND
Bitwise exclusive OR
Bitwise inclusive OR

16

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.9) Variables
1.9.1) Primitive Data Types
Java 8

Type
byte
short
int
long
float
double
boolean
char

Size (bits)
Default
8
0
16
0
32
0
64
0L
32
0.0f
64
0.0d
1
false
16 (Unicode Characters)
\u0000
Fig 2. Primitive Data Types

1.9.2) Arrays

int []arry1, []arry2;

// allocates dynamic arrays


int []arry1 = {1, 2, 3, 4, 5};
array

int []anArray;
anArray = new int[10];

// allocates memory for 10 integers

array

String[][] names = {{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}};

17

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.10) Enumerate
Variable Enumerate

Example
enumerate
property ID
public enum EVENT_TYPE {
SERVICE(1),
LINK(2),
SUBSCRIBER(4),
SMS(8),
WAP(16),
MMS(32),
BLOCK_LIST(64),
REPORT_DAILY(128),
REPORT_SUMMARY(256),
REPORT_MONTHLY(512),
REPORT_SMSDOWNLOAD(1024),
LOG_IN(2048),
LOT_OUT(4096);
private final int id;
EVENT_TYPE(final int id) {
this.id = id;
}
public int getId() {
return id;
}
public static EVENT_TYPE fromId(final int id) {
for (EVENT_TYPE e : EVENT_TYPE.values()) {
if (e.id == id) {
return e;
}
}
return null;
}
}
public enum EVENT_ACTION {
NONE(0),
ADD(1),
DELETE(2),
MODIFY(4),
SEARCH(8),
EXPORT(16),
IMPORT(32);
private final int id;
EVENT_ACTION(final int id) {
this.id = id;
}
public int getId() {

18

Learning Java
Training Course Out-Line
}

Author: Kittisak Lorniti


Email: [email protected]

return id;

public static EVENT_ACTION fromId(final int id) {


for (EVENT_ACTION e : EVENT_ACTION.values()) {
if (e.id == id) {
return e;
}
}
return null;
}

19

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.11) Control Flow Statements


1.11.1) The if-then and if-then-else statements
1.11.1.1) if-then statements
Example
void applyBrakes(){
if (isMoving){
currentSpeed--; // slow down speed
}
}
1.10.1.2) if-then-else Statements
Example
void applyBrakes(){
if (isMoving){
currentSpeed--; // slow down speed
} else {
System.err.println("The bicycle has already stopped!");
}
}
1.11.2) The switch-case statements
Example
class SwitchDemo {
public static void main(String[] args) {

int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");
}

}
1.11.3) Loop statements
1.11.3.1) while-do & do-while

20

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

while-do
while (conditions-to-do){
// your code goes here
}


do {
statement(s)
} while (conditions-to-do);

1.11.3.2) for loop


for () {...}
for (int x=0; x < 10; x++) {
// to do statements
}

1.11.3.4) for each


array
String []employee = {manee, piti, mana};
int i = 0;
for (String name : employee) {
System.out.println(Employee No. + (++i) + : + name);
}

Employee No.1 : manee


Employee No.2 : piti
Employee No.3 : mana

21

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

1.12) Error and exceptions handler


handle

Java

debug software


1.12.1) try-catch
try/catch statement code handle error

try {
// statements
} catch (exception-classname variable-name) {
// to do something to handle the exception
}
1.12.2) try-catch-finally
keyword finally
statements
transactions database /

finally

try {
// open file
} catch (exception-classname variable-name) {
// to do something to handle the exception
} finally {
// close file
}

1.12.3) throws Exception


method
method
Java keyword throws Exception method

void applyBrakes() throws Exception {
if (isMoving){
currentSpeed--; // slow down speed
} else {
throw new Exception(The bicycle has already stopped!);
}

22

Learning Java
Training Course Out-Line
}

Author: Kittisak Lorniti


Email: [email protected]

// do other actions

keyword throw
method

void applyBrakes() throws Exception {
try {
if (isMoving){
currentSpeed--; // slow down speed
}
} catch (Exception e) {
throw e;
}
}

23

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

Q&A

24

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

Advanced Java Programming

25

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2) Advanced Java Programming


section Standard Java Libraries


requirement
2.1) Concurrency and Synchronization

method sequential Java



synchronized
Example
public class TestSynchronized extends Thread {
public TestSynchronized(String s) {
super(s);
}
@Override
public void run() {
synchronized (TestSynchronized.class) {
String t = Thread.currentThread().getName();
System.out.println(t + " : " + "enter f()");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
//
}
System.out.println(t + " : " + "leaving f()");
}
}
public static void main(String[] args) throws Exception {
String[] nameThread = {"A", "B", "C", "D", "E"};
for (int i = 0; i < 5; i++) {
new TestSynchronized(nameThread[i]).start();
}
}

A
A
D
D
E
E
C
C
B
B

:
:
:
:
:
:
:
:
:
:

enter f()
leaving f()
enter f()
leaving f()
enter f()
leaving f()
enter f()
leaving f()
enter f()
leaving f()

26

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.2) Collection & Map

Array
Java
Collections
Collections
implement

Collections
Collections 3 Set, List Queue
Collections variable Map

27

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.2.1) Set
(unique)
Example
// Create the set
Set set = new HashSet();
// Add elements to the set
set.add("a");
set.add("b");
set.add("c");
// Remove elements from the set
set.remove("c");
// Get number of elements in set
int size = set.size();
// 2
// Adding an element that already exists in the set has no effect
set.add("a");
size = set.size();
// 2
// Determining if an element is in the set
boolean b = set.contains("a"); // true
b = set.contains("c");
// false
// Iterating over the elements in the set
Iterator it = set.iterator();
while (it.hasNext()) {
// Get element
Object element = it.next();
}

28

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.2.2) List
index
Example
// Create the list
List list = new LinkedList();
list = new ArrayList();
array

// Doubly-linked list
// List implemented as growable

// Append an element to the list


list.add("a");
// Insert an element at the head of the list
list.add(0, "b");
// Get the number of elements in the list
int size = list.size();
// 2
// Retrieving the element at the end of the list
Object element = list.get(list.size()-1);
// a
// Retrieving the element at the head of the list
element = list.get(0);
// b
// Remove the first occurrence of an element
boolean b = list.remove("b");
// true
b = list.remove("b");
// false
// Remove the element at a particular index
element = list.remove(0);
// a

29

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.2.3) Queue Stack (FIFO)

Example
// Create the queue
Queue queue = new LinkedList();
// Using the add method to add items.
// Should anything go wrong an exception will be thrown.
queue.add("a");
queue.add("b");
//Using the offer method to add items.
//Should anything go wrong it will just return false
queue.offer("c");
queue.offer("d");
//Removing the first item from the queue.
//If the queue is empty a java.util.NoSuchElementException will be thrown.
System.out.println("remove: " + queue.remove());
//Checking what item is first in line without removing it
//If the queue is empty a java.util.NoSuchElementException will be thrown.
System.out.println("element: " + queue.element());
//Removing the first item from the queue.
//If the queue is empty the method just returns false.
System.out.println("peek: " + queue.peek());
//Checking what item is first in line without removing it
//If the queue is empty a null value will be returned.
String tmp = null;
while ((tmp = (String) queue.poll()) != null) {
System.out.println("poll: " + tmp);
}

30

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.2.4) Map
Example
HashMap hm = new HashMap();
hm.put("Somchai", new Double(3434.34));
hm.put("Manee", new Double(123.22));
hm.put("Pusin", new Double(1200.34));
hm.put("Thana", new Double(99.34));
hm.put("Kasin", new Double(-19.34));
Set set = hm.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.println(me.getKey() + " : " + me.getValue());
}
//deposit into Somchai's Account
double balance = ((Double) hm.get("Somchai")).doubleValue();
hm.put("Somchai", new Double(balance + 1000));
System.out.println("Somchai new balance : " + hm.get("Somchai"));

31

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.3) Database Connection using JDBC



library jconnector
2

1. Import library jconnector Application Server


1.1 copy mysql-connector-java-5.1.10-bin.jar <GlassfishDomain>/lib/ext
1.2 restart Application Server
2. Library project
database test user test
C:\>"c:\Program Files\MySQL\MySQL Server 5.1\bin\mysql.exe" -u root ppassword < learningJava_db_setup.sql

Example
import java.sql.*;
public class getmySQLConnection
{
public static void main(String[] args)
{
DB db = new DB();
Connection conn=db.dbConnect(
"jdbc:mysql://localhost:3306/test", "test", "passwo
rd");
}
}
class DB
{

tance();
(

public DB() {}
public Connection dbConnect(String db_connect_string,
String db_userid, String db_password)
{
try
{
Class.forName("com.mysql.jdbc.Driver").newIns
Connection conn = DriverManager.getConnection
db_connect_string, db_userid, db_password);
System.out.println("connected");
return conn;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}

32

Learning Java
Training Course Out-Line
};

Author: Kittisak Lorniti


Email: [email protected]

33

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.4) DBCP Database Connection Pool


web application

connection
1. resource memory transaction
2. connection connection
DBCP
connection pool

pool
connection
DBCP class DBPoolManager
open source apply
XML config config
connect Database Mysql, MSSql, Oracle, etc.
DBCP
Example
1. XML configuration

<Glassfish_Domain>/conf/dbcp_test.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<dbDriverName>com.mysql.jdbc.Driver</dbDriverName>
<dbUser>test</dbUser>
<dbPassword>password</dbPassword>
<dbURI><![CDATA[jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEn
coding=UTF8&autoReconnect=true&zeroDateTimeBehavior=convertToNull]]></dbURI>
<dbPoolMinSize>10</dbPoolMinSize>
<dbPoolMaxSize>30</dbPoolMaxSize>
</config>
DBCP

34

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.4) Caching
database overhead
caching

callcenter
memory

memory


Example
public class ObjectFactory {
protected List<Object> objectList;
static int MAX_POOL_SIZE = 100;
static float FACTOR = 0.75f;
// shared cache memory
static
static Hashtable objectFactory
= new Hashtable(MAX_POOL_SIZE, FACTOR);
// method
public static Object getMessage(int id) throws Exception {
Object object = null;
//
cache DB
if (!objectFactory.containsKey(id)
|| (object = objectFactory.get(id)) == null) {
System.out.println("caching, object " + id);
object = new LoadFromDB(id);
//
cache
if (objectFactory.size() > (MAX_POOL_SIZE * FACTOR)) {
removeOlder(MAX_POOL_SIZE / 2);
}
if (objectFactory.containsKey(id)) {
objectFactory.remove(id);
}
objectFactory.put(id, object);

}
return object;

private static void removeOlder(int count) {


// remove an oldest object
Vector v = new Vector(objectFactory.keySet());
Collections.sort(v);
Enumeration e = v.elements();
int deleted = 0;
while (e.hasMoreElements()) {
objectFactory.remove(e);
if ((++deleted) >= count) {
break;
}

35

Learning Java
Training Course Out-Line
}

Author: Kittisak Lorniti


Email: [email protected]

public static void remove() {


// remove an oldest object
Vector v = new Vector(objectFactory.keySet());
Collections.sort(v);
Enumeration e = v.elements();
if (e.hasMoreElements()) {
objectFactory.remove(e);
}
}
}

36

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.5) Timer
Timer Schedule

Example
// stateless EJB class timer
public class TimerScheduleLearningJavaDemo implements
TimerScheduleLearningJavaDemoRemote {
@Resource
TimerService timerService;
// trigger
enum TimedEvent {
EVERY_7_SECONDS(7 * 1000, 0),
EVERY_8_SECONDS(8 * 1000, 0),
EVERY_9_SECONDS(9 * 1000, 0),
EVERY_10_SECONDS(10 * 1000, 0),
EVERY_11_SECONDS(11 * 1000, 0),
EVERY_12_SECONDS(12 * 1000, 0),
EVERY_13_SECONDS(13 * 1000, 0),
EVERY_14_SECONDS(14 * 1000, 0),
HOURLY(3600 * 1000, 0),
DAILY(24 * 3600 * 1000, 4 * 3600 * 1000),
WEEKLY(7 * 24 * 3600 * 1000, 4 * 3600 * 1000),
MONTHLY(1000, 0);
final long interval;
final long offset;
private TimedEvent(long interval, long offset) {
this.interval = interval;
this.offset = offset;
}
public long getInterval() {
return interval;
}

public long getOffset() {


return offset;
}

// initialize timer
public void scheduleTimers() {
// timer

for (Object timerObj : timerService.getTimers()) {


Timer timer = (Timer) timerObj;
if (timer.getInfo() instanceof TimedEvent) {
timer.cancel();
}
}
// timer TimedEvent
long now = System.currentTimeMillis();
37

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

for (TimedEvent te : TimedEvent.values()) {


if (te == TimedEvent.MONTHLY) {
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.set(Calendar.HOUR, 4);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.MONTH, 1);
timerService.createTimer(cal.getTime(), te);
} else {
timerService.createTimer(te.interval + te.offset,

te);

}
@Timeout
public void timerFired(Timer timer) {
TimedEvent evt = (TimedEvent) timer.getInfo();
try {
// TimedEvent
switch (evt) {
case EVERY_7_SECONDS:
case EVERY_8_SECONDS:
case EVERY_9_SECONDS:
case EVERY_10_SECONDS:
case EVERY_11_SECONDS:
case EVERY_12_SECONDS:
case EVERY_13_SECONDS:
case EVERY_14_SECONDS:
// to do something on this trigger
System.out.println(evt);
break;
case HOURLY: // do stuff we do every hour
System.out.println("timer hourly.");
break;
case DAILY: // do stuff we do every day at midnight
System.out.println("timer daily.");
break;
case WEEKLY: // do stuff we do every week
System.out.println("timer weekly.");
break;
case MONTHLY: // Have to manually schedule the next
one, months are not fixed length
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.set(Calendar.HOUR, 4);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.MONTH, 1);
timerService.createTimer(cal.getTime(), evt);

}
} finally {

System.out.println("timer monthly.");
break;

38

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

// timer

timerService.createTimer(evt.interval + evt.offset, evt);
}

}
TimerSchedule class deploy application
process
context listener servlet
Example
1. package LearningJavaDemoApp-war -> Source Packages
2. new -> Web Application Listener Context Listener
3. Alt+Insert lookup stateless EJB
TimerScheduleLearningJavaDemoRemote
4. implement code contextInitialized(...)
public class init implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
// initialize timer schedule
lookupTimerScheduleLearningJavaDemoRemote().scheduleTimers();
}
public void contextDestroyed(ServletContextEvent sce) {
throw new UnsupportedOperationException("Not supported
yet.");
}
private TimerScheduleLearningJavaDemoRemote
lookupTimerScheduleLearningJavaDemoRemote() {
try {
Context c = new InitialContext();
return (TimerScheduleLearningJavaDemoRemote)
c.lookup("java:comp/env/TimerScheduleLearningJavaDemo");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE,
"exception caught", ne);
throw new RuntimeException(ne);
}
}
}

39

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.6) File Operation



Example
try {

// Open the file that is the first


// command line parameter
FileInputStream fistream =
new FileInputStream("c:/tmp.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fistream);
// new file
FileOutputStream fostream =
new FileOutputStream("c:/tmp2.txt");
DataOutputStream out = new DataOutputStream(fostream);
try {
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the text on the console
System.out.println(strLine);
out.write(strLine.getBytes());
}
} finally {
//Close the input stream
in.close();
out.close();
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

40

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.7) XML simple utilization with SAXBuilder


Example
SAXBuilder builder = new SAXBuilder();
try {
File f = new
File("D:/nack_work/glassfish/domains/staging/config/dbcp_test.xml");
if (!f.exists() || !f.canRead())
throw new
FileNotFoundException("D:/nack_work/glassfish/domains/staging/config/
dbcp_test.xml");
Document doc = builder.build(f);
Element root = doc.getRootElement();
String dbDriverName =
root.getChild("dbDriverName").getTextTrim();
String dbUser = root.getChild("dbUser").getTextTrim();
String dbPassword =
root.getChild("dbPassword").getTextTrim();
String dbURI = root.getChild("dbURI").getTextTrim();
int dbPoolMinSize =
Integer.parseInt(root.getChild("dbPoolMinSize").getTextTrim());
int dbPoolMaxSize =
Integer.parseInt(root.getChild("dbPoolMaxSize").getTextTrim());
System.out.println("dbDriverName : " + dbDriverName);
System.out.println("dbUser : " + dbUser);
System.out.println("dbPassword : " + dbPassword);
System.out.println("dbURI : " + dbURI);
System.out.println("dbPoolMinSize : " + dbPoolMinSize);
System.out.println("dbPoolMaxSize : " + dbPoolMaxSize);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

- memory input
- elementName

41

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.8) XML performance utilization with JAXB


JAXB Class Sun XML
memory resource
request.xml
<?xml version="1.0" encoding="utf-8" ?>
<XML>
<USERNAME>test</USERNAME>
<PASSWORD>test</PASSWORD>
<COMMAND>REGISTER</COMMAND>
<MESSAGEID>F2U Ref. ID (Generated by F2U)</MESSAGEID>
<OPERATORID>52001</OPERATORID>
<SERVICENUMBER>4761YYY</SERVICENUMBER>
<PACKAGEID>XX</PACKAGEID>
<CHANNEL>1</CHANNEL>
<MSISDN>668XXXXXXXX</MSISDN>
<MESSAGE>*4761YYYZZ</MESSAGE>
<TIMESTAMP>2009-12-05 22:00:12</TIMESTAMP>
<STATUSCODE>1003</STATUSCODE>
<STATUSTEXT>Success</STATUSTEXT>
</XML>
XML Java Class xml2xsd xjc tool
/usr/sbin/xml2xsd request.xml.request request.xsd
xjc -p com.java.training.xml.request request.xsd
.java package com.java.training.xml.request

42

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.8.1) Unmarshaller
XML
1. class netbeans package project build
.jar
2. import .jar library modules method
function XML XML
Example
pubic void unmarshalXml(String data) throws JAXBException {
com.java.training.xml.request.XML xml = null;
try {
JAXBContext jc =
JAXBContext.newInstance("com.java.training.xml.request");
// create an Unmarshaller
Unmarshaller u = jc.createUnmarshaller();
// unmarshal a news instance document into a tree of Java content
xml = (com.java.training.xml.request.XML)
u.unmarshal(new StreamSource(new StringReader(data)));
// print out details of xml
...
} catch (JAXBException e) {
throw new e;
}
}

43

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.8.2) Marshaller
XML JAXB

Example
import com.java.training.xml.request.XML;
public void main(String args[]) {
try {
XML xml = new XML();
xml.setUSERNAME((user);
xml.setPASSWORD((password);
xml.setCOMMAND(command);
xml.setMESSAGEID(msgid);
xml.setOPERATORID(1);
xml.setSERVICENUMBER(1234);
xml.setPACKAGEID(pkgid);
xml.setCHANNEL(1);
xml.setMSISDN(66844678748);
xml.setMESSAGE(Hello);
xml.setTIMESTAMP(DatetimeUtil.print());
xml.setSTATUSCODE(2);
xml.setSTATUSTEXT(SUCCESS);
StringWriter sw = new StringWriter();
JAXBContext jc =
JAXBContext.newInstance("com.java.training.xml.request ");
Marshaller m = jc.createMarshaller();
m.marshal(xml, sw);
System.out.println(sw.getBuffer().toString());

} catch (Exception e) {
e.printStackTrace();
}

44

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.9) Servlet Programming


Servlet POST GET
console
1. Web Application Project ServletTraining context
training
2. Package java.training.servlet web application >
source package
3. new servlet ServletExam1 context servlet_exam1

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain;charset=UTF-8");
OutputStream os = response.getOutputStream();
try {
java.io.InputStream inputStream =
request.getInputStream();
String encoding = "UTF-8";
if (request.getCharacterEncoding() != null) {
encoding = request.getCharacterEncoding();
}
Reader rd = new InputStreamReader(inputStream, encoding);
StringBuffer strbuf = new StringBuffer();
int c;
int rest = contentLength;
while ((c = rd.read()) != -1) { // read until EOF
strbuf.append((char) c);
if (--rest <= 0) {
break;
}
}
System.out.println(strbuf.toString());

os.write(OK);
} finally {
os.close();
}

45

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.10) Socket Programming (HTTP)


HTTP poster HTTP packet servlet 2.9
public static void main(String[] args) {
// TODO code application logic here
String url = "http://127.0.0.1:8080/training/servlet_exam1";
String data = "Hello Java Servlet";
HttpPost hp = new HttpPost();
try {
hp.setContenttype("application/x-www-form-urlencoded");
hp.setUrl(url);
OutputStream os = hp.getWriter();
Writer w = new OutputStreamWriter(os, "UTF-8");
w.write(data);
w.close();

String resp = hp.getResponse();


} catch (Exception e) {
e.printStackTrace();
} finally {
hp.disconnect();
}

46

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.11) Socket Programming (Continue)


HTTP poster XML 2.8.2 Marshaller
servlet ServletExam2 context = servlet_exam2
HTTP packet XML 2.8.1
Class package com.java.training.xml.response
response 2.8.2
xml response
<?xml version="1.0" encoding="utf-8" ?>
<XML>
<STATUSCODE>1000</STATUSCODE>
<STATUSTEXT>Success</STATUSTEXT>
<MESSAGEID>12345</MESSAGEID>
<REFID> packet request </REFID>
</XML>

47

Learning Java
Training Course Out-Line

Author: Kittisak Lorniti


Email: [email protected]

2.9) Session Control in Servlet


1. project ServletTraining Package java.training.session
web application > source package
2. new servlet ServletExam3 context servlet_exam3

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String name = request.getParameter("name");
if (name != null) {
sname = name;
request.getSession().setAttribute("name", name);
}
String current_name =
(String) request.getSession().getAttribute("name");
out.println("<H1>name(keep in session):" +
current_name + "</H1>");
out.println("<H1>Session ID:" +
request.getSession().getId() + "</H1>");
} finally {
out.close();
}
}

48

Learning Java
Training Course Out-Line
-

Author: Kittisak Lorniti


Email: [email protected]

Data Types, I/O and Operators


Decision Statements: if-else, switch-case
Iteration Statements: while, do-while, for, for each
String Operations
File Operations
Arrays
list
HashMap
Function / Methods
OOP
Error handle
Synchronization

Day 2, Advanced Java Programming (Timer Scheduler + Database


Connector & DBCP + Socket programming (HTTP with authentication) +
Servlet programming + JSP) ( ) + Practice with demo application (
demo app)
- install Java Glassfish v2.1 config
- JAVA EE netbeans IDE deploy
library
- Timer Scheduler Job
- Database DBCP
- Socket programming (HTTP)
- Java Servlet JSP
Day 3, Practice with demo application (continue) + Q/A
- OCR library (image recognize) bot
- bot
- Job
- automated form submit
-

49

You might also like