# Heading 1 (Arial, 12 pt, B, I)

Software and s/w Development

Oct 28, 2013 (4 years and 6 months ago)

128 views

Title

(Arial
,

12

pt, B
)

(
Arial
,
1
2

pt
, B, I
)

(
Arial
, 12

pt
, I
)

(
Arial
, 11

pt
, B, I
)

(
Arial
, 11

pt

,I
)

Normal

(Arial
, 10

pt)

Code (Courier New, 8 pt)

1. Pointers and Arrays

-

Pointer Arithmetic

-

Function Calls (Pas
s by value, Pass by reference)

-

String Manipulation

-

Command
-
line Arguments

-

Pointers to Void

2. Structures

-

Memory Allocation (automatic and dynamic objects)

3. Input and Output

-

Standard I/O

-

Synchronization

5. Abstraction Mechani
sms in C++

-

-

Templates

-

Exception Handling

6. Windows Data Types (winnt.h)

7. Windows API in C++

-

MFC (Classes, Functions)
ANSI C and C++

Pointers and Arrays

Pointer Arithmetic

int

i = 5; // sets the value of i to 5

int

*p = NUL
L; // initializes an integer pointer to NULL

p = &i; // sets the value of p to be the address of i

*p = 8; // sets the value of i to be 8

// i = 8, &i = 0x22ff44, p = 0x22ff44, &p = 0x22ff40, *p = 8

Function Calls

Pass by value

It co
pies the
value

of an argument to the corresponding parameter in the called
function

C or C++:

void

swap(
int

x,
int

y) {
int

temp = x; x = y; y = temp; }

int

a = 10;
int

b = 20; swap(a, b);
// a = 10, b = 20

Declaring parameters const is a way of reducing
the number of errors you produce.

int

foo(
const

double bar);

Pass by reference

It passes the

(a pointer to it) of an argument to the corresponding parameter
in the called function

C:

void

swap(
int

*x,
int

*y) {
int

temp = *x; *x = *y; *y = temp; }

int

a = 10;
int

b = 20; swap(&a, &b);
// a = 20, b = 10

C++:

void

swap(
int

&x,
int

&y) {
int

temp = x; x = y; y = temp; }

int

a = 10;
int

b = 20; swap(a, b);
// a = 20, b = 10

String Manipulation

char

*str1 = "Hello World"; // char str1[] or in C++ strin
g str1

char

*str2 = (
char

*) malloc(strlen(str1+1)); // +1 for '
\
0'

char

*str3 = (
char

*) malloc(5+1);

//str2 = str1; // copies the pointer, not the characters

strcpy(str2, str1); // Hello World

memcpy(str3, str1+6, 5); // World

// *(str1+6) = W; str1+6
= World

int

i = strcmp(str3, str2); // 1 as str3[1] > str2[1]

int

j = strcmp(str2, str3); //
-
1 as str2[1] < str3[1]

Command
-
line Arguments

int

main(
int

argc,
char

*argv[]){}

int

main(
int

argc,
char

**argv){}

-

argc is the number of arguments, and argv
is an array of strings that contains the
arguments.

Pointers to Void

The generic pointer type void * is used for the pointer arguments. Any pointer can be
cast to type void * and back again without loss of information.

int

compare(
void

*a,
void

*b){}

Str
uctures

Memory Allocation (automatic and dynamic objects)

typedef struct

_point point;

struct

_point

{

int

x;

int

y;

};

point p1;
// in the stack

point *p2 = (point *) malloc(
sizeof
(point));
// in the heap

_point p3;

// C++, in the stack

_point

*p4 = new _point();

// C++, in the heap

p1.x = 5; p2
-
>x = 10; p3.x = 15; p4
-
>x = 20; // (*p4).x = 20;

free(p2); delete p4;

Input and Output

Standard I/O

#include <stdio.h>
// C

#include <iostream>
// C++

using namespace

std;
// C++

i
nt

x;

scanf("%d", &x); printf("%d
\
n", x);
// C

cin >> x; cout << x << endl;
// C++

getchar(); // get a character from the standard input

Abstraction Mechanisms in C++

Objective: the same operation

is performed on multiple, different
data types
.

Define
only operators that inherently modify the value of their first argument, such as +=, in
the class itself. Operators that simply produce a new value based on the values of its
arguments, such as +, are defined outside the class.

Syntax: [
friend] <
data
-
type> operator

<op>

([
<data
-
type> <variable
-
identifier>
[,
<data
-
type>

<variable
-
identifi er>
]]);

class

complex {

double

re, im;

public
:

complex
&

operator

+= (complex a);

}

complex
operator

+

(complex a, c
omplex b)

{

complex r

=

a;

return

r += b;
//access representation through +=

}

Templates

Standard Template Library (STL)

-

algorithm

-

iterator

-

list

-

map

-

set

-

stack

-

queue

-

vector

Member functions:

operator[]: access element

at: access eleme
nt with exception handling

front: access first element

back: access last element

size: return size

push_back: add element at the end with increasing the vector size by one

pop_back: delete last element

insert: insert elements

erase: erase elements

vector<
int
> v;

for

(
int

i = 0; i < 5; i++)

v.push_back(i);

for

(vector<
int
>::iterator it = v.begin(); it != v.end(); ++it)

cout << *it << '
\
t';

Exception Handling

#include <stdexcept>

#include <iostream>

using namespace

std;

float

dividend = 1, divi
sor = 0;

try

{

if

( divisor == 0 ) {

throw

invalid_argument("Invalid argument exception.");

}
else if

( divisor ==
-
1 ) {

throw

out_of_range("Out of range exception.");

}

cout << dividend / divisor << endl;

}
catch

(
const

exception& e) {

cout << e.what() << endl;

}
catch

(...) {

cout << "Handle all exceptions." << endl;

}

Case Study

person.h

#ifndef PERSON_H

#define PERSON_H

#include <iostream>

using namespace

std;

class

Person

{

string name;

int

age;

int
* holiday;

public
:

P
erson(
const

string& n,
const int
& a);

~Person();

//virtual ~Person(); // derived class is destroyed too

string getName()
const

{
return

name; }

// inline

int

getAge()
const

{
return

age; }

// inline

int

getHoliday(
int

year)
const throw

(exceptio
n&);

void

int

year,
int

occasion = 1)
throw

(exception&);

Person
operator

+ (
int

n)
const
;

};

extern const

string defaultName;

//global function because the left operand is not a class!

ostream&
operator

<< (ostream& out,
const

Person& p);

#endif

person.cpp

#include "person.h"

#include <stdexcept>

const

string defaultName = "Calvin";

Person::Person(
const

string& n,
const int
& a)

: name(n), age(a)

{

holiday =
new int
[age];

for

(
int

i = 0; i < age; i++) {

holiday[i] = 0;

}

}

Person::~Person()

{

delete
[] holiday;

}

int

Person::getHoliday(
int

year)
const throw

(exception&)

{

if

(year > age) {

throw

out_of_range("Out of range exception.");

}
else

{

return

holiday[year];

}

}

void

int

ye
ar,
int

occasion)
throw

(exception&)

{

if

(year > age) {

throw

out_of_range("Out of range exception.");

}
else

{

holiday[year
-

1] = occasion;

}

}

Person Person::
operator

+ (
int

n)
const

{

return

Person(name, age

+

n);

}

ostream&
oper
ator

<< (ostream& out,
const

Person& p)

{

out << p.getName() << ": " << p.getAge() << ". Holidays: [ ";

for

(
int

i = 0; i < p.getAge(); i++) {

out << p.getHoliday(i) << " ";

}

out << "]";

return

out;

}

main.cpp

#include "person.h"

int

ma
in()

{

Person p(defaultName, 10);

// Calvin: 10. Holidays: [ 0 0 0 0 0 0 0 0 0 0 ]

cout << p << endl;

// Calvin: 10. Holidays: [ 0 0 1 0 0 0 0 0 0 2 ]

cout << p << endl;

// Calvin: 15. Holidays
: [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]

cout << p + 5 << endl;

try

{

}
catch

(
const

exception& e) {

cout << "year cannot be greater than age for holiday" << endl;

}

cin.get();

return

0;

}

Windows Development Refe
rence

Windows Data Types (winnt.h)

typedef int

BOOL;

typedef

BYTE BOOLEAN;

typedef unsigned char

BYTE;

typedef unsigned long

DWORD;

typedef void

*HANDLE;

typedef
HANDLE HINSTANCE;

typedef

HINSTANCE HMODULE;

typedef signed int

INT32;

typedef signed long lon
g

INT64;

typedef long long

LONGLONG;
// _M_IX86

typedef double

LONGLONG;

typedef long

LPARAM;

typedef const unsigned short

*LPCTSTR;
// UNICODE

typedef const char

*LPCTSTR;

typedef unsigned int

UINT;

typedef unsigned short

WORD;

typedef unsigned int

WPAR
AM;

MFC (Microsoft Foundation Classes)

Classes

Data Types:

-

CString

-

CTime

-

CTimeSpan

-

CArray

-

CList

-

CMap

Windows:

-

CDialog: CCommonDialog, CPropertyPage

-

CControlBar: CDialogBar, CStatusBar, CToolBar

-

CSplitterWnd

-

CPropertySheet

-

CFrameWnd:
CMDIChildWnd, CMDIFrameWnd

-

CView: CCtrlView (CEditView, CListView, CRichEditView, CTreeView), CScrollView

-

CTreeCtrl

-

CButton

(
check bo
: CBitmapButton

-

CComboBox: CComboBoxEx

-

CEdit

-

CListBox: CCheckListBox, CDragList
Box

-

CProgressCtrl

-

CRichEditCtrl

-

CScrollBar

-

CSliderCtrl

-

CSpinButtonCtrl

-

CStatic

-

CTabCtrl

TODO (
sample
code)

CTreeCtrl: ItemHasChildren, GetChildItem,
GetNextSiblingItem, GetRootItem, GetSelectedItem, GetItemText, GetItemData,
SetItemData, Inse
rtItem, DeleteAllItems, SortChildren

Functions

Data Exchange

DDX_Text: binds an edit control to a CString data member

DDX_Check: binds a check box control to a int data member

DDX_CBIndex: binds
a combo box control to a int data member

DDX_LBIndex: binds a list box control to a int data member

DDX_Scroll: binds a scroll
-
bar control to a int data member

DDX_Slider: binds a slider control to a int data member

DDX_Control: binds a subclassed control
to a CWnd data member

TODO (
try code
)

void

{

CDialogEx::DoDataExchange(pDX);

DDX_Control(pDX, IDC_OK, m_ok);

}

ON_
BN_CLICKED(IDC_OK, OnOK)

END_MESSAGE_MAP()

void

{

AfxGetApp()
-
>GetMainWnd()
-
>MessageBox("OK");

}

Synchronization

Prevents two threads from reading and writing to shared memory at the same time.

TODO (
)

#include <windows.h
>

HANDLE lock;
// Handle to an Object

void

void

*pArgs)

{

WaitForSingleObject(lock, INFINITE);

int

i;
for

(i = 0; i < 5000; i++) printf("W ");

ReleaseMutex(lock);

}

int

main(
void
)

{

lock = CreateMutex(NULL, FALSE, NULL);

_beginthre

WaitForSingleObject(lock, INFINITE);

int

j;
for

(j = 0; j < 5000; j++) printf("R ");

ReleaseMutex(lock);

getchar();

return

0;

}

JNI (Java Native Interface)

Java code ↔ C/C++ code

(wrapper classes)

JNI Functions (JNI

Native

Interface)

Version Information

Class Operations

FindClass: This function loads a locally
-
defined class. It searches the directories and
zip files specified by the CLASSPATH environment variable for the class with the
specified name.

Exceptions

Throw
New: Constructs an exception object from the specified class with the message
specified by message and causes that exception to be thrown.

Global and Local References

NewGlobalRef: Creates a new global reference to the object referred to by the obj
argumen
t. The obj argument may be a global or local reference
.

DeleteLocalRef: Deletes the local reference pointed to by localRef.

Weak Global References

Object Operations

NewObject: Constructs a new Java object.

GetObjectClass: Returns the class of an object.

Ac
cessing Fields of Objects

GetFieldID: Returns the field ID for an instance (nonstatic) field of a class.

Get<type>Field: Returns the value of an instance (nonstatic) field of an object.

Calling Instance Methods

GetMethodID: Returns the method ID for an ins
tance (nonstatic) method of a class or
interface.

CallVoidMethod: Accepts the arguments and passes them to the Java method that
the programmer wishes to invoke.

CallVoidMethodV: Accepts the arguments and passes them to the Java method in an
argument of ty
pe that the programmer wishes to invoke.

Accessing Static Fields

Calling Static Methods

String Operations

NewStringUTF: Constructs a new java.lang.String object from an array of characters
in modified UTF
-
8 encoding.

Array Operations

GetArrayLength: Return
s the number of elements in the array.

NewObjectArray: Constructs a new array holding objects in class elementClass.

SetObjectArrayElement: Sets

an element of an Object array.

New<PrimitiveType>Array: Constructs a new primitive

array object.

Get<Primitive
Type>ArrayElements: Returns the body of the primitive array.

Get<PrimitiveType>ArrayRegi on
: Copies a region of a primitive

array into a buffer.

Set<PrimitiveType>ArrayRegion
:

Copies back a region of a primitive

array from a
buffer.

Registering Native Metho
ds

Monitor Operations

NIO Support

Reflection Support

Java VM Interface

GetJavaVM: Returns the Java VM interface (used in the Invocation API) associated

The Invocation API (JNI

Invoke

Interface)

The Invocation API allows softwar
e vendors to load the Java VM into an arbitrary
native application.

Invocation API Functions

http://docs.oracle.com/javase/1.5.0/docs/guide/jni/

Case Study

ascetcom.h

// CodeComponent_Dispatch wrapper class

class

CodeComponent_Dispatch :
public

C
O
leDispatchDriver

{

public
:

CodeComponent
_Dispatch() {}

// Calls C
O
leDispatchDriver default constructor

CodeComponent_Dispatch(LPDISPATCH

pDispatch):C
O
leDispatchDriver(pDispatch){}

CodeComponent_Dispatch(
const

CodeComponent_Dispatch& dispatchSrc) :

COleDispatchDriver(dispatchSrc) {}

//
Attributes

public
:

// Operations

public
:

dComponent(LPDISPATCH Parameter0,
LPCTSTR Parameter1);

};

ascetcom.cpp

LPCTSTR Parameter1)

{

LPDISPATCH result;

static

BYTE parms[] = VTS_DISPATCH VTS_BSTR;

InvokeHelper(
dispid, DISPATCH_METHOD, VT_DISPATCH, (
void
*)&result, parms,

Parameter0,
Parameter1);

RELEASEIDOFNAME

return

result;

}

1.
Create a Java class that declares
the native method

KBW_CodeComponent.j
ava

/**

* Wrapper class of CodeComponent.

*/

public class

KBW_CodeComponent{

/**

*
subcomponent to this component.

In most general case we add classes

*
to

the modules.

*
@param component is the componen
t to be referred from this code component.

*
@param name is the desired name of reference.

*
@throws ConfiguratorException if the code component contains an other

*
reference with the same name.

*
@return with the new reference of component.

*/

publi
c

native

component,
String name)
throws

ConfiguratorException
;

}

2.
Use javac to compile the program

KBW_CodeComponent.
class

3.
Use javah to generate header file

KBW_CodeComponent.h

KBW_CodeCo
mponent.h

/
*

*
Class: Java_com_knorrbremse_ascet_wrapper_KBW_lCodeComponent

*

*
Signature:

(Lcom_knorrbremse_
ascet_wrapper_KBW_l
Code
Component;L
java_lang_String;)Lcom_kno
rrbr
ems
e_ascet_wrapper_KBW_lComplexMod
elElement;

*/

JNIEXPORT

jobject JNICALL

t
(JNIEnv *,

jobject,
jobject, jstring);

4.
Write the C implementation of the native method

KBW_CodeComponent.
cpp

/
*

*
Class: Java_com_knorrbremse_ascet_wrapper_
KBW_lCodeComponent

*

* Signature:
(Lcom_knorrbremse_asce
t_wrapper_KBW_lCodeComponent;Lj
ava_lang_
String;)Lcom_kno
rrbremse_ascet_
wrapper_KBW_lComplexModelElement;

*/

JNIEXPORT jobject JNICALL

Java_com
_knorrbremse_ascet_wrapper_KBW
_
lCodeComponent_
(

JNIEnv
*env, jobject obj, jobject objComponent,
jstring name)

{

jclass c
ls = env
-
>GetObjectClass(obj);

jfie
ldID dpField = env
-
>GetFieldID(cls,
"dp", "J");

jlong dpCodeComponent = env
-
>GetLongField(obj, dpField);

C
odeComponent_Dispatch *d
p =
(CodeComponent_Dispatch*)dpCodeComponent;

jclass clsComponent = env
-
>GetObjectClass(objComponent);

jfieldID dpFieldComponent =
env
-
>GetFieldID(clsComponent,
"dp", "J");

jlong dpComponent = env
-
>GetLongField(objComponent
, dpFieldComponent);

CodeCompo
nent_Dispatch *dc =
(CodeComponent_Dispatch*)dpComponent;

jclass cmeCls = env
-
>FindClass

("com/knorrbremse/ascet/wrapper/KBW_ComplexModelElement");

jmethodID cmeClsConstruct
or = env
-
>GetMethodID(cmeCls,
"<init>"
,"(J)V");

GETSTRING(name);

LPDISPATCH tempDp = dp
-

if

(!tempDp)

{

FREESTRING(name);

jclass exception = env
-
>FindClass

("com/knorrbremse/esra/configurator/ConfiguratorException");

env
-
>ThrowNew(exc
eption,
"Unexpected exception occured!");

return

0;

}

ComplexModelEle
ment_Dispatch *cmeObj =
new

ComplexModelElement_Dispatch(tempDp)
;

jobject retu
rnObj = env
-
>NewObject(cmeCls, cmeClsConstructor,
(jlong)cmeObj);

FREESTRING(name);

r
eturn

returnObj;

}

5.
Compile C code and generate native library

AscetTool.dll

6.
Run the program using the Java interpreter

Java EE Programming

Three
-
tier architecture

Client

Thin client (e.g. browser) and thick client (e.g. desktop application).

Web server (web container)

E.g. GlassFish, Apache Tomcat, JBoss.

Application server

E.g. GlassFish (EJB container), Apache Tomcat, JBoss.

Database server

E.g. MySQL, Oracle, MSSQL.

Enterprise JavaBeans (EJB) Settings

GlassFish Application Server in IDE

Server Port Number: 8080

Domain Name: domain1

MySQL Database Server in GlassFish

h
ttp://localhost:4848/

c:
\
Program Files
\
glassfish
-
3.1.1
\
glassfish
\
lib
\
mysql
-
connector
-
java
-
5.0.8
-
bin.jar

2. New JDBC Connection Pool

Resources/JDBC/JDBC Connection Pools

Pool Name: MySQLPool

Resource Type: javax.sql.Con
nectionPoolDataSource

Database Vendor: MySQL

URL: jdbc:mysql://localhost:3306/uml2008

driverClass: com.mysql.jdbc.Driver

serverName: localhost

portNumber: 3306

databaseName: uml2008

user: root

3. New JDBC Resource

Resources/JDBC/JDBC Resources

JNDI Name: jdbc/mysql

Pool Name: MySQLPool

Modules of Enterprise Applications

1. New Enterprise Application Project

-

Create EJB module (runs on Application Server) and Web module (runs in Web
Container) through this projec
t.

Note: Tomcat is not an EJB Container, but EJB support can be added to Tomcat
using OpenEJB or JPA.

Note: Deploying On Eclipse make sure J2EE Module Dependencies contains the
EJB and Web modules in project properties of Enterprise Application.

2. New En
tity and Session Bean classes in the EJB module

-

Generate persistence.xml (through Entity Class Wizard)

NetBeans:

DemoApp
\
DemoEJB
\
src
\
conf
\
persistence.xml

Eclipse:

DemoEJB
\
ejbModule
\
META
-
INF
\
persistence.xml

<?xml version="1.0" encoding="UTF
-
8"?>

<persis
tence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema
-
instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

<persistence
-
unit name="DemoEJBPU" transaction
-
type="JTA">

<jta
-
data
-
source>jdbc/mysql</jta
-
data
-
source>

<exclude
-
unlisted
-
classes>false</exclude
-
unlisted
-
classes>

<properties/>

</persistence
-
unit>

</persistence>

3. New Servlet in the Web module

-

Gener
ate web.xml (through Servlet Wizard)

NetBeans:

DemoApp
\
DemoWeb
\
web
\
WEB
-
INF
\
web.xml

Eclipse:

DemoWeb
\
WebContent
\
WEB
-
INF
\
web.xml

<?xml version="1.0" encoding="UTF
-
8"?>

<web
-
app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w
3.org/2001/XMLSchema
-
instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web
-
app_3_0.xsd">

<servlet>

<servlet
-
name>RegisterServlet</servlet
-
name>

<servlet
-
class>org.web.RegisterServlet</ser
vlet
-
class>

</servlet>

<servlet
-
mapping>

<servlet
-
name>RegisterServlet</servlet
-
name>

<url
-
pattern>/RegisterServlet</url
-
pattern>

</servlet
-
mapping>

</web
-
app>

4. Clean and Build DemoApp, Run DemoApp (on Server)

Deployment of
Enterprise Applications

1. Start GlassFish

-

NetBeans:

Services window

-

Eclipse:

JavaEE perspective

-

-
-
domain)

2. List of Deployed Enterprise Applications

-

DemoApp.e
ar contains DemoEJB.jar and DemoWeb.war

-

http://localhost:8080/DemoWeb/RegisterServlet

3. Start MySQL

-

MySQL Administrator (Schemas with Tables in Catalogs)

Sample EJB 3.0 Application

Ent
ity Bean

Persistence (data model): saves the state of object into database (serialization) and
restores database (deserialization).

User.java

package

org.domain;

import

java.io.Serializable;

import

javax.persistence.*;

@Entity

@Table(name = "users")

@Na
medQueries({

@NamedQuery(name = "User.findAll",

query = "SELECT u FROM User u"),

@NamedQuery(name = "User.findByUserId",

query = "SELECT u FROM User u WHERE u.userId = :userId")})

public class

User
implements

Serializable {
// It
is important to be
Serializable!

static final

long

serialVersionUID = 1L;

private

Long userId;

private

private

private

Country country;

public

User() {}

public

User(Long userId) {
this
.userId =

userId; }

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

@Column(name = "USER_ID")

// Annotations shall always be placed for the getter methods!

public

Long getUserId() {
return

userId; }

public void

setUserId(Long userId) {
this
.userId = userId; }

@Column(name = "USERNAME", columnDefinition = "TEXT")

public

return

public void

this

inition = "TEXT")

public

return

public void

this

// No mappedBy
-
> This class is responsible for relation (one Country).

@ManyToOne(fetch = FetchT
ype.LAZY)

@JoinColumn(name = "COUNTRY_ID")

public

Country getCountry() {
return

country; }

public void

setCountry(Country country) {
this
.country = country; }

}

Country.java

package

org.domain;

import

java.io.Serializable;

import

java.util.Li
st;

import

javax.persistence.*;

@Entity

@Table(name = "countries")

public class

Country
implements

Serializable {

static final

long

serialVersionUID = 1L;

private

Long countryId;

private

String name;

private

List<User> people;

public

Country() { }

public

Country(Long countryId) { this.countryId = countryId; }

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

@Column(name = "COUNTRY_ID")

public

Long getCountryId() {
return

countryId; }

public void

setCountryId
(Long countryId) {
this
.countryId = countryId; }

@Column(name = "NAME", columnDefinition = "TEXT")

public

String getName() {
return

name; }

public void

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

// Other side (many Users).

@OneToM
any(fetch = FetchType.LAZY, mappedBy = "country")

public

List<User> getPeople() {
return

people; }

public void

setPeople(List<User> people) {
this
.people = people; }

}

OneToMany Relation

Session Bean

s): manages the entity through persistence context.

UserManagerLocal.java

package

org.services;

import

javax.ejb.Local;

import

org.domain.User;

// Application Server and Web Container are in the same JVM.

@Local

public interface

UserManagerLocal {

p
ublic

public void

updateUser(User user);

public void

deleteUser(Long id);

String RunQuery();

}

UserManagerBean.java

package

org.services;

import

java.util.List;

import

javax.persistence.*;

import

javax.ejb.Stateless;

i
mport

org.domain.User;

@Stateless

public class

UserManagerBean
implements

UserManagerLocal {

@PersistenceContext

private

EntityManager em;

@Override

public

em.persist(user);

em.flush();

r
eturn

user.getUserId();

}

@Override

public void

updateUser(User user) {

user = em.merge(user);

}

@Override

public void

deleteUser(Long id) {

User user = em.find(User.
class
, id);

em.remove(user);

}

@Override

public

String RunQuery() {

String s = "Query:"; //
EJB
-
QL

try

{

// 1. Dynamically from code.

// Query query =

// em.createQuery("SELECT u FROM User u WHERE u.userId = 1356");

// 2. Named query from annotation.

Query query = em.createNamedQuery("User.findByUserId");

query.setParameter("userId", 1956L);

// 3. Elements named
-
query in orm.xml.

// Query query = em.createNamedQ
uery("getUser");

List<User> users = query.getResultList();

for

(User uu: users) {

s += " " + uu.getUserName();

}

}

catch

(Exception e) {

s += " " + e.g
etMessage();

}

return

s;

}

}

CountryManagerLocal.java

package

org.services; ...

CountryManagerBean.java

package

org.services; ...

The Life Cycle of Entities

Test Servlet (RegisterServlet.java)

package

org.web;

import

java.io.*
;

import

javax.ejb.EJB;

import

javax.servlet.*;

import

javax.servlet.http.*;

import

org.domain.*;

import

org.services.*;

public class

RegisterServlet
extends

HttpServlet
implements

Servlet {

static final

long

serialVersionUID = 1L;

@EJB

p
rivate

UserManagerLocal userManager;

@EJB

private

CountryManagerLocal countryManager;

public

RegisterServlet() {

super
();

}

@Override

protected void

doGet(HttpServletRequest request, HttpServletResponse
response)

throws

ServletException, IOException {

Country country =
new

Country();

country.setName("United States");

User user1 =
new

User();

User user2 =
n
ew

User();

//List<User> users = new ArrayList<User>();

//country.setPeople(users);

user1.setCountry(country);

user2.setCountry(country);

response.setContentType("text/html;charset=UTF
-
8");

PrintWriter out = response.getWriter();

try

{

out.println("<h1>Register users...</h1>");

" + country.getName());

out.println("<br/>");

out.println("<br/>" + userManager.RunQuery());

}
catch

(Exception e) {

out.println("<span>Operation failed:</span>");

out.println("<div><pre>");

e.printStackTrace(out);

out.println("</pre></div>");

}
finally

{

out.println("</bod
y></html>");

out.close();

}

}

@Override

protected void

doPost(HttpServletRequest request, HttpServletResponse response)

throws

ServletException, IOException {

doGet(request, response);

}

}

Java Pe
rsistence API (JPA) Settings (see EJB Settings)

Apache Tomcat Application Server in IDE

Server Location (Catalina Home): C:
\
Program Files
\
Apache Software
Foundation
\
Apache Tomcat 7.0.14

Server Port: 8080

Shutdown Por
t: 8005

MySQL Database Server in GlassFish (non
-
JTA persistence)

http://localhost:8080/

1. Define a user for GUI

c:
\
Program Files
\
Apache Software Foundation
\
Apache Tomcat 7.0.14
\
conf
\
tomcat
-
users.xml

<?xml version="1.0" encoding="UTF
-
8"?>

<tomcat
-
users>

-

<role rolename="manager
-
gui"/>

-
gui"/>

word="s3cret" roles="manager
-
-
gui"/>

</tomcat
-
users>

c:
\
Program Files
\
Apache Software Foundation
\
Apache Tomcat 7.0.14
\
lib
\
mysql
-
connector
-
java
-
5.0.8
-
bi n.jar

3. New JDBC Resource (JNDI Datasource)

c:
\
Program Fil
es
\
Apache Software Foundation
\
Apache Tomcat
7.0.14
\
conf
\
context.xml

<Context>

<Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"

maxActive="100" maxIdle="30" maxWait="10000"

qlroot"

driverClassName="com.mysql.jdbc.Driver"

url="jdbc:mysql://localhost:3306/uml2008"/>

</Context>

4. New JDBC Resource Reference

c:
\
Program Files
\
Apache Software Foundation
\
Apache Tomcat 7.0.14
\
conf
\
web.xml

<web
-
app ve
rsion="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema
-
instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web
-
app_3_0.xsd">

<resource
-
ref>

<description>DB Connection</description>

<res
-
ref
-
name>jdbc/mysql</res
-
ref
-
name>

<res
-
type>javax.sql.DataSource</res
-
type>

<res
-
auth>Container</res
-
auth>

</resource
-
ref>

</web
-
app>

5. New Session Customizer

ionCustomizer.java in a package

6. New Entity class in the application

-

Generate non
-
JTA (RESOURCE_LOCAL) persistence.xml (through Entity Class
Wizard)

<?xml version="1.0" encoding="UTF
-
8"?>

<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/p
ersistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema
-
instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

<persistence
-
unit name="DemoWebAppPU" transaction
-
type="RESOURCE_LOC
AL">

<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

<exclude
-
unlisted
-
classes>false</exclude
-
unlisted
-
classes>

<non
-
jta
-
data
-
source>java:comp/env/jdbc/mysql</non
-
jta
-
data
-
source>

<properties>

<property name

</properties>

</persistence
-
unit>

</persistence>

MySQL Database Server in IDE (persistence with direct connection)

1. New Entity class in the
application

-

Generate direct connection (RESOURCE_LOCAL) persistence.xml (through Entity
Class Wizard)

<?xml version="1.0" encoding="UTF
-
8"?>

<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLS
chema
-
instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

<persistence
-
unit name="DemoWebAppPU" transaction
-
type="RESOURCE_LOCAL">

<class>domain.User</class>

<propertie
s>

<property name="javax.persistence.jdbc.user" value="root"/>

<property name="javax.persistence.jdbc.driver"

value="com.mysql.jdbc.Driver"/>

<property name=
"javax.persistence.jdbc.url"

value="jdbc:mysql://localhost:3306/uml2008"/>

</properties>

</persistence
-
unit>

</persistence>

Sample JPA Application (See EJB 3.0 Application)

UserManager.java

package

services;

import

domain.User;

import

javax.persistence.*;

public class

UserManager {

private

EntityManager em;

public

UserManager(EntityManager em) {

this
.em = em;

}

public

em.persist(user);

return

user.getUserId
();

}

// Other methods.

}

RegisterServlet.java

package web;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import domain.*;

import services.*;

import javax.persistence.*;

public class RegisterServlet extends HttpServlet
implements Servlet {

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse
response)

throws ServletException, IOException {

EntityManagerFactory emf =

Persistence.createEntityManagerFactory("De
moWebAppPU");

EntityManager em = emf.createEntityManager();

UserManager userManager = new UserManager(em);

User user = new User();

//user.setUserId(56L);

ass");

EntityTransaction transaction = em.getTransaction();

synchronized (transaction) {

try {

transaction.begin();

transaction.commit();

} c
atch (IllegalStateException ex) {

System.out.println("Error " + ex.getMessage());

} catch (Exception ex) {

System.out.println("Error " + ex.getMessage());

if (transaction.isActive()) {

transaction.rollback();

}

} finally {

em.close();

emf.close();

}

}

// Other methods.

}

Java Server Pages (JSP)

-

Servlet: HTML code in Java

-

JSP (Java

Server Pages): Java code in HTML (by Sun)

-

ASP (Active Server Pages):
Visual Basic
code in HTML (by Microsoft)

Library: JSTL 1.1

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" pre
fix="c" %>

<sql:query var="rs" dataSource="jdbc/mysql">

SELECT id FROM users

</sql:query>

<html>

<title>DB Test</title>

<body>

<h2>Results</h2>

<c:forEach var="row" items="\${rs.rows}">

Id \${row.id}<br/>

</c:forEach>

</body>

</html>

Java Database Connectivity (JDBC)

-

JNDI (Java

Naming and Directory Interface
)

public static

Connection getConnection()
throws

SQLException {

String driver = "com.mysql.jdbc.Driver";

String url = "jdbc:mysql://lo
calhost:3306/uml2008";

String user = "root";

try

{

Class.forName(driver);

}
catch

(ClassNotFoundException ex) {

System.out.println("Error: failed to load JDBC driver.");

}

return

Driver

}

public static void

executeJDBC() {

Connection conn =
null
;

Statement stmt =
null
;

PreparedStatement ps =
null
;

try

{

conn = getConnection();

conn.setAutoCommit(false);

stmt = conn.createStatement();

stmt.executeUpdate("CREATE TABLE IF NOT EXISTS user (username
VARCHAR(20),

hdate)

values('user', '', '1985
-
12
-
31')");

conn.commit();

// Creates a result set containing all data from table using statement.

ResultSet rs = stmt.executeQuery("SELECT * FROM user

WHERE birthdate = '1987
-
12
-
31
'");

// Creates a result set containing all data from table using prepared
statement.

ps = conn.prepareStatement("SELECT * FROM user WHERE birthdate = ?");

ps.setDate(1,
new

java.sql.Date(567903600000L)); // date in
milliseconds.

rs = ps.executeQuery();

// Fetches each row from the result set.

while

(rs.next()) {

// Gets the data from the row using the column index.

java.sql.Date d = rs.getDate(3);

// Gets the data from t
he row using the column name.

d = rs.getDate("birthdate");

Calendar cal = Calendar.getInstance();

cal.setTime(d);

System.out.println("birthdate from user: " +

(cal.get(Calendar.YEAR)
-

1900));

}

}
catch

(SQLException ex) {

System.out.println("Database access error: " + ex.getMessage());

}
catch

(Exception ex) {

System.out.println("Error: " + ex.getMessage());

}
finally

{

try

{

conn.setAutoCommit(
true
);

ps.close();

stmt.close();

conn.close();

}
catch

(Exception ex) {

System.out.println("Error: " + ex.getMessage());

}

}

}