Curs Aplicatii distribuite

306
Bucuresti 2009 – 2010 CURS DAD Cristian TOMA [email protected] Departamentul de Informatica Economica DEZVOLTAREA APLICATIILOR DISTRIBUITE DISTRIBUTED APPLICATIONS DEVELOPMENT

description

Curs Aplicatii Distribuite Facultate

Transcript of Curs Aplicatii distribuite

Page 1: Curs Aplicatii distribuite

Bucuresti2009 – 2010

CURS DAD

Cristian [email protected]

Departamentul de Informatica Economica

DEZVOLTAREA APLICATIILOR DISTRIBUITE

DISTRIBUTED APPLICATIONS DEVELOPMENT

Page 2: Curs Aplicatii distribuite

Activitate didactica: Curs 50% + Laborator 50%12 cursuri 12 laboratoare

Modalitate evaluare: Examen scris – in curs 13

Misiune: Însuşirea elementelor teoretice si practice privind dezvoltarea aplicatiilor distribuite utilizandlimbaje evoluate de programare si tehnologii orientate obiect.

Structura Disciplinei

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 3: Curs Aplicatii distribuite

Programa Analitica

* Elemente si concepte in dezvoltarea aplicatiilor distr ibuite

SecŃiunea I – Programare orientata obiect in JSE

SecŃiunea II – Protocoale de retea programabile in JSE

SecŃiunea III – Programare web orientata obiect in JEE

SecŃiunea IV – Programare distribuita orientata pe apelu ri la distanta, componente si servicii in JEE

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 4: Curs Aplicatii distribuite

� Explicare notiuni elementare JDK, JRE, JVM

� Compilare in linie de comanda si in mediu – NetBeans

� Conceptele: clasa, obiect, interfata, derivare si poli morfism => late-binding => orice metoda Java este virtuala, ori ce obiect pointer

� Mecanismul de clonare si gestiune minimala a erorilor – try-catch

SecŃiunea I – Programare orientata obiect in JSE

Fundamentele limbajului JAVA

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 5: Curs Aplicatii distribuite

� Java Generics

� Java Annotations & Java Reflection

� Java Collection Framework

� I/O Stream & Java Libraries

� Clase si metode de tip factory & Clase Singleton

� JNI – Java Native Interface

� Procese si Fire de executie – Threads

SecŃiunea I – Programare orientata obiect in JSE

Elemente avansate ale limbajului JAVA

Page 6: Curs Aplicatii distribuite

� TCP – Transmission Control Protocol� RFC 793

� UDP – User Datagram Protocol� RFC 768

� HTTP – HyperText Transport Protocol� RFC 2616 – 1.1 si RFC 1945 – 1.0

� FTP – File Transport Protocol� RFC 959

SecŃiunea II – Protocoale de retea programabile in JSE

Protocoale programate prin socket

DEZVOLTAREA APLICATIILOR DISTRIBUITE

� ARP/RARP

� ICMP

� LDAP

� DNS

� DHCP

Programare in retea – Socket & Programare Client-Server

Page 7: Curs Aplicatii distribuite

SecŃiunea II – Protocoale de retea programabile in JSE

Protocoale programate prin socket

� SMTP – Simple Mail Transport Protocol� RFC 821

� POP3 – Post Office Protocol� RFC 1939 si RFC 2449

� IMAP4 – Internet Message Access Protocol� RFC 1730 si RFC 3501

� SNMP – Simple Networking Management Protocol� RFC 1157

� RMI/RPC – Remote Method Invocation / Remote Procedure Call� RFC 1050 si RFC 1057

� RFC 2713

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 8: Curs Aplicatii distribuite

� JNDI – Java Naming Directory Interface

� XML DOM & SAX – optional

� JDBC – Java Database Connectivity – optional

� Java Servlet

� JSP – Java Server Pages & Taglibs

� Componente Bean & Java Mail

� Transpunere tehnologie JSP&Servlet in HTTP

� MVC: Spring

SecŃiunea III – Programare web orientata obiect in JEE

JAVA Enterprise Edition

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 9: Curs Aplicatii distribuite

Sectiunea IVProgramare distribuita orientata pe apeluri la dist anta,

componente si servicii in JEE

� RMI – Remote Method Invocation

� Servicii Web – SOAP – Simple Object Application Protoc ol

� Programare orientata pe componente/agenti – CORBA

� Programare sincrona vs asincrona: JMS queues vs top ics

� Componente EJB – Enterprise Java Beans

SecŃiunea IV – Programare distribuita in JEE

Java Enterprise Edition

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 10: Curs Aplicatii distribuite

Obiective de indeplinit

Elemente ale misiunii

Programare JEE� RMI, JNDI si CORBA� Java Servlet & JSP� Java Beans� Java Web Services� EJB

Elemente de retea� TCP & UDP� SNMP� SMTP, POP3, IMAP4� FTP� HTTP

Administrare servere� Apache Tomcat 6.0 � Glass Fish v2.0 & JBOSS

Programare orientata obiect in JSE� Java Generics & Java

Annotations � Java Collection Framework� I/O Stream & Java Libraries� Clase si metode de tip factory

& Clase Singleton� JNI – Java Native Interface� Fire de executie – Threads� Programare in retea – Socket� Java Reflection

Page 11: Curs Aplicatii distribuite

Obiective de indeplinit

Elemente ale misiunii

Dezvoltarea aplicatiilor distribuite prin:

� Apel proceduri la distanta – RMI

� Servicii Web – SOAP

� CORBA

� JMS

� Componente EJB – Enterprise Java Beans

Page 12: Curs Aplicatii distribuite

Grup tinta al disciplinei DAD

Input & Output

Studenti� Cunostinte de C� Cunostinte de C++

Specialisti entry level� Administrare retea� Administrare

servere web

Specialisti entry level� Dezvoltare aplicatii distribuite� Arhitecturi distribuite fiabile

Disciplina

“DezvoltareaAplicatiilorDistribuite”

Page 13: Curs Aplicatii distribuite

Tehnologii preponderent utilizate

JSE 40% + JEE 59% + C/C++ 1%

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 14: Curs Aplicatii distribuite

Referinte bibliografice

SecŃiunea I – Programare orientata obiect in JSE� http://java.sun.com

SecŃiunea II – Protocoale de retea programabile in JSE� http://java.sun.com� RFC 793, RFC 768, RFC 2616, RFC 1945, RFC 959, RFC 821, RFC 1939, RFC 2449, RFC 1730, RFC 3501, RFC 1157, RFC 1050, RFC 1057, RFC 2713� TCP/IP Red Book – IBM Press

SecŃiunea III – Programare web orientata obiect in JEE� http://java.sun.com

SecŃiunea IV – Programare distribuita orientata pe apelu ri la distanta, componente si servicii in JEE

� http://java.sun.com

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 15: Curs Aplicatii distribuite

DAD – Dezvoltarea Aplicatiilor Distribuite

Curs marti – sala 2204, ora 16:30 & Laboratoare in 2001 D

1. Trebuie sa invatam la aceasta disciplina?� BINEINTELES …

2. Trebuie sa ne schimbam mentalitatea prin care pr ofu’ spune la curs si laborator ceva si noi apoi acasa nu lucram?

� DESIGUR …3. Cum va fi evaluare la aceasta disciplina?

� Test grila in sesiune cu secvente de cod … NOTA la eval uare este o consecinta, un efect – NU ESTE o cauza si un scop

4. Se poate pica la aceasta disciplina?� BINEINTELES …

5. Cum se invata la aceasta disciplina?� Utilizand cursul, laboratorul, materialele bibliograf ice plus compilatoarele, depanatoarele, modelul de memorie si analiza de trafic … => NU TREBUIE invatat pe dinafara� Combinand MEMORIA vizuala + auditiva + kinetica� + CREATIVITATE, GANDIRE si AUTOINSTRUIRE

Mod organizare & F.A.Q

Page 16: Curs Aplicatii distribuite

Curs 0

Agenda

1. Teoria sistemelor distribuite

Page 17: Curs Aplicatii distribuite

Curs 0

Sistem distribuit

Ce este un sistem distribuit?

Pentru noţiunea de sistem distribuit sau sistem de calculdistribuit, există în literatura de specialitate câteva definiţii, maimult sau mai puţin echivalente.

Astfel, un sistem distribuit este o colecţie de noduri, care pot fi:� calculatoare;� procesoare;� procese autonome

Page 18: Curs Aplicatii distribuite

Curs 0

Sistem distribuit

Ce este un sistem distribuit?

În Tanenbaum definirea este mai restrictivă, considerându-se căun sistem este distribuit numai dacă:

existenţa nodurilor autonome este transparentă pentruutilizatorul obişnuit.

Intreg ansamblul este o entitate de sine stătătoare, întreagaregie de distribuire trecând în sarcina nucleelor sistemelor de operare operaţionale în noduri. Cu alte cuvinte, utilizatorul unuisistem distribuit nu este conştient că există mai multeprocesoare; sistemul arată ca un singur procesor virtual.

Page 19: Curs Aplicatii distribuite

Curs 0

Sistem distribuit

Clasificarea sistemelor distribuite

� Sisteme distribuite strâns conectate – strong coupled, în care de regulă mai multe procesoare partajează aceeaşi memorieinternă şi consultă acelaşi ceas – mainframes, transputere.

� Sisteme distribuite slab conectate – loose coupled, în care fiecare sistem are propria memorie şi propriul lui ceas

Fără să existe o acceptarea unanimă, sistemeleconectate slab sunt identificate cu sistemele distribuite.

Page 20: Curs Aplicatii distribuite

Curs 0

Sistem distribuit

Ce este un sistem distribuit?Deci un sistem distribuit este:

o colecŃie de programe şi procese peste o reŃea de echipamente electronice care cooperează în rezolvareaanumitor probleme:

- în care fiecare nod are autonomie locală – propiul ceas şipropria memorie internă,

- iar nodurile în ansamblul lor sunt transparente pentruutilizator în ideea realizării obiectivului urmărit de sistemuldistribuit.

Page 21: Curs Aplicatii distribuite

Curs 0

Sistem distribuit

Ce fenomene exista intr-un sistem distribuit?

Cel mai important fenomen este cel de migrare. Fenomenulde migrare se manifestă în trei direcŃii:

� migrarea datelor;

� migrarea calculelor;

� migrarea proceselor.

Programarea distribuit ă are ca principal obiectivtratarea distribuirii calculelor.

Page 22: Curs Aplicatii distribuite

Curs 0

Sistem distribuit

Avantaje:Schimbul de informaŃii. Creşterea masivă a cantităŃii de informaŃie şinecesitatea de a schimba rapid informaŃii între diferitele puncte aflate în locurigeografic depărtate fac necesară conectarea între calculatoare autonome.

Partajarea resurselor. O organizaŃie preferă să cumpere mai multecalculatoare mai ieftine şi de puteri rezonabile decât să cumpere unul singur, mult mai puternic dar mult mai scump. În acest mod devine necesarăinterconectarea acestor calculatoare mai mici între ele, eventual cu un numărredus de calculatoare mai puternice ale căror resurse (memorie, putere a procesorului, periferice de capacităŃi mari) să fie partajate între acestea.

SiguranŃă mărită în funcŃionare. Dacă un sistem de calcul este format dintr-un singur calculator, defectarea acestuia face imposibilă utilizarea întreguluisistem, pe cand intr-un sistem distribuit, căderea unui nod nu perturbăfuncŃionarea celorlalte, ci acestea preiau sarcinile celui căzut.

Page 23: Curs Aplicatii distribuite

Curs 0

Sistem distribuit

Avantaje:

PerformanŃe mărite. PrezenŃa mai multor procesoare într-un sistem distribuitface posibilă reducerea timpului de realizare a unui calcul masiv. Acest fapteste posibil prin împărŃirea sarcinilor între diferite procesoare, colectareaulterioară a rezultatelor parŃiale şi determinarea rezultatului final. Acestprocedeu este cunoscut sub numele de paralelizare a calculului.

Specializarea nodurilor. Proiectarea unui sistem de calcul autonom cu maimulte funcŃionalităŃi poate să fie foarte dificilă şi din motive practice. Aceastăproiectare poate să fie simplificată prin împărŃirea sistemului în module, fiecare modul implementând o parte din funcŃionalităŃi şi comunicând cu altemodule.

Page 24: Curs Aplicatii distribuite

Curs 0

Sistem distribuit Caracteristici:• suport pentru partajarea resurselor= aceleasi resurse sunt folosite de mai multi utilizatori;

• deschiderea= sistemul poate fi extins pe diferite căi;

• concurenta= mai mulţi utilizatori folosesc aceeaşi resursă în acelaşi timp;

• paralelism= un proces pentru a-şi soluţiona problema foloseşte în acelaşi timp diferiteresurse;

• scalabilitate= sistemul acţionează efectivşi eficient pe diferite scale (datorităeterogenitatiii resurselor);

• toleranta la erori= când apar accidente sistemul le rezolvă bazându-se pe redundanţahardware si acoperirea software;

• transparenta= gradul de independenţă între componentele sistemului (resurse, utilizatori, etc) la funcţionare.

Page 25: Curs Aplicatii distribuite

Curs 0

Sistem distribuit Transparenta:

• transparenţa accesului = obiectele (informaţia) locale sau la distanţă vor fiaccesate utilizând operaţii identice;• transparenţa localizării = obiectele vor fi accesate fără a se cunoaşte poziţia lorîn reţea;• transparenţa concurenţei = mai multe procese pot opera concurenţial (în acelaşitimp), utilizând obiecte partajate, fără să interfereze între ele şi fără ca utilizatorulsă remarce acest lucru;• transparenţa replicării = multiple copii ale obiectelor pot fi utilizate pentrucreşterea performanţei, fără ca utilizatorii sau programele de aplicaţie săcunoască replicările (copiile pe diferite noduri din reţea);• transparenţa accidentelor = ascunderea erorilor;• transparenţa migrării = mutarea obiectelor în sistem (informaţii, date, calcule, procese) nu trebuie să afecteze operaţiile utilizatorilor sau programelor de aplicaţie;• transparenţa performanţelor = sistemul va fi reconfigurat automat la diferiteîncărcări pentru creşterea performanţelor.

Page 26: Curs Aplicatii distribuite

Curs 0

Algoritmi distribuiti Probleme:

� Lipsa cunoştinŃelor despre starea globală. În fluxul de control al unuialgoritm centralizat deciziile se pot lua în funcŃie de starea întreguluisistem.

� Lipsa unui timp global. Evenimentele care constitue executarea unuialgoritm centralizat formează o mulŃime total ordonată, relaŃia de ordinefiind cea naturală, conform cu apariŃia temporală a acestor evenimente.

� Pseudo-Nedeterminismul. Comportamentul unui program centralizatpoate fi descris în funcŃie de datele de intrare. Pentru acelaşi set de date de intrare, comportamentul unei aplicaŃii este identic la rulăridiferite (exceptând cazurile în care se rulează programe ce trateazăsubiecte din inteligenŃa artificială). La distribuit poate varia“nedeterminist” viteza de prelucrare, ordinea de tratare a clientilor data de intarzierile de transmisie, etc.

Page 27: Curs Aplicatii distribuite

AGENDA Curs 1 – SECTIUNEA 1

Partea I – Elemente fundamentale utilizate pentru dezvoltarea unui program Java

� Linie de comanda + Notepad + JDK/JRE 5.0 si 6.0

� Mediu NetBeans 6.5 + NetBeans 6.7

Partea II – Clase si obiecte

� Necesitatea metodei clone

� Model de memorie

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 28: Curs Aplicatii distribuite

Curs 1

Partea I – Elemente fundamentale utilizate pentru dezvoltarea unui program Java

Partea I

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Ce este o masina virtuala?

Trebuie asociata unei masini virtuale o masina de stari?

Care sunt avantajele si care sunt dezavantajele?

Exemplu program Hello World

Compilare linie de comanda cu JDK 5.0

Compilare in NetBeans 6.0.1

Page 29: Curs Aplicatii distribuite

Curs 1

Partea II – Clase si obiecte

Partea II

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Ce este o clasa?

Ce este un pachet de clase?

Ce este un obiect?

Cati octeti ocupa un obiect?

Necesitatea metodei clone

Demo si model de memorie pe clasa certificat

Page 30: Curs Aplicatii distribuite

AGENDA Curs 2

Partea I – Derivare/Mostenire, Polimorfism, Interface as type in Java, Vectori de obiecte, Null pointer reference

Partea II – Java Generics

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 31: Curs Aplicatii distribuite

Curs 2

Partea I – Derivare/Mostenire, Polimorfism, Interface as type in Java

Partea I–Derivare/Mostenire/Polimorfism

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Polimorfismul – “abilitatea de a lua mai multe forme” se asigura prin:� Supra-incarcare metodelor unei clase � methods overloading� Varianta pura:

� Mecanism de mostenire/derivare – “extends is the key word”� Metodelor virtuale – “in Java by default”� Supradefinirea metodelor virtuale� Utilizarea obiectelor de tip pointer/referinta – “in Java by default”

Interfata – “contract intre clasa care implementeaza interfata si programatorul in calitate de utilizator al interfetei” – poate contine:

� Doar campuri statice� Doar prototip de metode statice si non-statice� In implementare se utilizeaza cuvant cheie “implements ”� Se pot declara obiecte de tip interfata dar nu si instantia

Page 32: Curs Aplicatii distribuite

Curs 2

Partea I – Derivare/Mostenire, Polimorfism, Interface as type in Java

Partea I–Derivare/Mostenire/Polimorfism

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Clasa abstracta – “o clasa care are cel putin o metoda abstracta” – poatecontine:

� Macar o metoda abstracta – cuvant cheie “abstract ”� Poate contine metode statice si non-statice� Se pot declara DAR NU se pot instantia obiecte dintr-o clasa abstracta

*ATENTIE la: Obiecte si vectori de obiecte + null pointer exception

Page 33: Curs Aplicatii distribuite

Curs 2

Partea I – Derivare/Mostenire, Polimorfism, Interface as type in Java

Partea I–Derivare/Mostenire/Polimorfism

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Care sunt avantajele derivarii si mostenirii?

Care sunt avantajele polimorfismului?

Ce este o interfata? Ce este o clasa abstracta?

Care sunt avantajele si care sunt dezavantajele utilizarii “Interface as type”?

Exemplu program derivare/mostenire, polimorfism

Exemplu program in NetBeans vizual din UML – Interfata, Clasa, Derivare, Polimorfism

Page 34: Curs Aplicatii distribuite

Curs 2

Partea II – Java Generics

Partea II – Java Generics

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Recomandarile pentru denumiril parametrilor sunt:

* E - Element (utilizat extensiv in Java Collections Framework)* K - Key* N - Number* T - Type* V - Value* S,U,V etc. - 2nd, 3rd, 4th types

Page 35: Curs Aplicatii distribuite

Curs 2

Partea II – Java Generics

Partea II – Java Generics

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Care sunt avantajele programarii generice?Transforma eroarea din “run-time in compile-time”

Are loc o macroexpandare ca in C/C++ in cadrul programarii generice?NU

Unde este utilizata programarea generica?In mod intensiv incepand cu JDK 5.0 si in special in Java Collection Framework

ATENTIE de citit din tutoriale java.sun.com – Java Generics concepte: “Sub-typing”, “WildCards”, “Type-Erasure”

Exemplu program Java Generics – Generics1.java si Generics4.java

Page 36: Curs Aplicatii distribuite

AGENDA Curs 3

Partea I – Java Collection FrameworkCombinare de Java Generics + Interface as type

Partea II – Java Reflection – java.lang.reflect.*;

Partea III – Java Annotations – java.lang.annotation.*;

Exemplu compus Java Reflection + Annotations

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 37: Curs Aplicatii distribuite

Curs 3

Partea I – JCF

� JCF – Java Collection Framework este o ierarhie de clase, claseabstracte si interfete care definesc si implementeaza lucrul cu structuride date standard: vector, lista – stiva/coada, arbore binar de cautare, Hashtable

� In JCF sunt create interfete, implementari si algoritmi

� Lucrul cu JCF presupune lucru cu interfete (interface as type) in loc de lucru cu implementari (cu clase)

� Ierarhia de clase este bazata pe:� Collection – defineste o valoare pentru fiecare element� Map – defineste cate o pereche de valori, cheie-valoare pentru

fiecare element

Page 38: Curs Aplicatii distribuite

Curs 3

Partea I – JCF

DEZVOLTAREA APLICATIILOR DISTRIBUITE

<<interface>> Iterable<T>

<<interface>> Collection<E> <<interface>>

Map<K,V>

java.util.*

<<interface>> List<E>

<<interface>> Set<E>

Vector<E> ArrayList<E> LinkedList<E> TreeSet<E> HashSet<E> LinkedHashSet<E> TreeMap<K,V> HashMap<K,V> Hashtable<K,V>

Page 39: Curs Aplicatii distribuite

Curs 3

Partea I – JCF

1. Lucrul cu JCF presupune lucru cu interfete (interface as type) in loc de lucru cu implementari (cu clase)

2. Traversarea se face cu foreach sau iteratori (partial utilizand clasa Enumeration pentru Vector si Hashtable)a. for(Object o : collection) System.out.println(o);b. for(Iterator<?> it = collection.iterator(); it.hasNext();)

System.out.println(it.next())

3. Ordinea obiectelor in Colectii (inclusiv pentru utilizarea algoritmilor de sortare etc) este data de implementarea metodei “compareTo(...)” din interfata Comparable<T> sau utilizarea interfetei Comparator<T> prin implementarea metodei “compare(...)”

4. Pentru optimizare se recomanda pentru structurile de tip hash implementarea metodelor mostenite din Object “hashCode()” si “equals(...)”

Page 40: Curs Aplicatii distribuite

Curs 3

Partea II – Java Reflection

DEZVOLTAREA APLICATIILOR DISTRIBUITE

� Java Reflection este o “tehnica introspectiva” utilizata de programe cenecesita “abilitati” de examinare sau modificare a comportamentului la rulare a claselor din interiorul masinii virtuale Java

� Java Reflection este o tehnica relativ avansata si trebuie utilizata doarde programatori ce au cunostinte temeinice ale conceptelorfundamentale din limbajului Java.

� Java Reflection este o tehnica care permite diverselor aplicatii saexecute operatii care altfel ar fi imposibile. Nu exista o tehnica similarain alte limbaje de programare. Microsoft C# este singurul limbaj care a copiat aceasta tehnica.

Page 41: Curs Aplicatii distribuite

Curs 3

Partea II – Java Reflection

Partea II

Exemple pentru plecand de la obiecte si vector de obiecte:� Operatorul instanceof

� Afisarea metodelor unei clase

� Obtinerea informatiilor despre constructori

� Obtinerea de informatii despre campurile claselor

� Invocarea metodelor dupa nume

� Crearea de noi obiecte

� Modificarea valorilor din campuri

� Utilizarea vectorilor in contextul de Java Reflection

Page 42: Curs Aplicatii distribuite

Curs 3

Partea II – Java Reflection

Partea II

In ce tip de aplicatii se poate utiliza Java Reflection?Class BrowsersDebuggersTest Tools

Care sunt dezavantajele tehnicii Java Reflection?Performanta – deoarece se interfereaza la nivel de “byte-code”, anumite elementede optimizare ale JVM nu pot fi aplicateRestrictii de securitate – aproape imposibil de aplicat la Java Applet – Security Manager ModuleExpunerea elementelor interne ale clase – campuri si metode private ce pot genera disfunctionalitati – in mod normal nu se recomanda a fi accesate

Vom utiliza aceasta tehnica pentru aceasta disciplina?DA – exemplu de server FTP DA – in combinatie cu adnotarile la EJB 3.0 si Servicii Web

Page 43: Curs Aplicatii distribuite

Curs 3

Partea III – Java Annotations

DEZVOLTAREA APLICATIILOR DISTRIBUITE

� Java Annotation “is the meta-tags that you will use in your code to give it some life.”

� Exista 2 elemente diferite: “annotation type ” si “annotation ”

� Definire adnotare – “ annotation type ” :

public @interface MyAnnotation { String doSomething();

}

� Utilizare adnotare – “annotation ”:

@MyAnnotation (doSomething="What to do") public void mymethod() { .... }

Page 44: Curs Aplicatii distribuite

Curs 3

Partea III – Java Annotations

Trei tipologii de “ annotation type ” :

� 1. Marker – nu are elemente interneExemplu:

public @interface MyAnnotation { } Utilizare:

@MyAnnotationpublic void mymethod() { .... }

� 2. Single Element – are un singur element reprezentat de cheie=valoareExemplu:

public @interface MyAnnotation { String doSomething();

} Utilizare:

@MyAnnotation ("What to do") public void mymethod() { .... }

Page 45: Curs Aplicatii distribuite

Curs 3

Partea III – Java Annotations

Tipologii de “ annotation type ” :

� 3. Full-Value sau Multi-Value – nu are elemente interneExemplu:

public @interface MyAnnotation { String doSomething(); int count; String date();

}

Utilizare:

@MyAnnotation (doSomething="What to do", count=1, date="09-09-2005") public void mymethod() { .... }

Page 46: Curs Aplicatii distribuite

Curs 3

Partea III – Java Annotations

Reguli pentru definirea adnotarilor – “ annotation type ” :

1. Declararea unei adnotari trebuie sa inceapa cu ‘@interface’ urmat de numele adnotarii.

2. Metodele declarate nu au parametrii.3. metodele declarate nu au clauze de “aruncare exceptii”.4. Tipurile de date ale unei metode sunt:

* primitive – byte, char, int, float, double, etc.* String* Class* enum* vectori de unul din tipurile enumerate anterior – int[], float[], etc.

Page 47: Curs Aplicatii distribuite

Curs 3

Partea III – Java Annotations

Exista in JDK 5.0 adnotari simple/predefinite – “ annotation ” :

1. @Override2. @Deprecated3. @SupressWarnings

Page 48: Curs Aplicatii distribuite

Curs 3

Exista in JDK 5.0 adnotari de adnotari – “ meta-annotation ” ce se aplica doartipurilor de adnotari “ annotation type ” :

1. Target@Target(ElementType.TYPE) @Target(ElementType.FIELD)@Target(ElementType.METHOD) @Target(ElementType.PARAMETER) @Target(ElementType.CONSTRUCTOR)@Target(ElementType.LOCAL_VARIABLE) @Target(ElementType.ANNOTATION_TYPE)

2. Retention- @Retention(RetentionPolicy.SOURCE) – retinute la niv el cod sursa si

sunt ignorate de compilator- @Retention(RetentionPolicy.CLASS) – retinute la nive l de compilare dar

ignorate de VM la run-time- @Retention(RetentionPolicy.RUNTIME) – sunt retinute si utilizate doar la

run-time

3. Documented – @Documented

4. Inherited – @Inherited

Page 49: Curs Aplicatii distribuite

AGENDA Curs 4

Partea I – Java Libraries & IO Streams

Partea II – Java Native Interfaces – JNI

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 50: Curs Aplicatii distribuite

Curs 4

Partea I – Librarie Java

Ce este o librarie Java?

Cum se creaza o librarie Java?

Care sunt avantajele utilizarii librariilor Java?

Care sunt dezavantajele utilizarii librariilor Java?

Page 51: Curs Aplicatii distribuite

Curs 4

Partea I – I/O Streams Java

� I/O Streams permite lucrul cu interfete, clase abstracte, clase si metodepentru a accesa consola si pentru a citi/scrie din/in dispozitive periferice siretea

� Package-urile java.io.*; si java.nio.*;

� Se lucreaza la nivel de octet – byte si caracter – char = 2 bytes

� ATENTIE la encodari – ISO8859-1, ISO8859-2, UTF16LE si UTF16BE

Page 52: Curs Aplicatii distribuite

Curs 4

Partea I – I/O Streams Java – byte level

Page 53: Curs Aplicatii distribuite

Curs 4

Partea I – I/O Streams Java – byte level

Page 54: Curs Aplicatii distribuite

Curs 4

Partea I – I/O Streams Java – char level

Page 55: Curs Aplicatii distribuite

Curs 4

Partea I – I/O Streams Java – char level

Page 56: Curs Aplicatii distribuite

Curs 4

Partea I – I/O Streams Java – File

Object File

<<interface>> Serializable

<<interface>> Comparable<File>

<<interface>> Closeable

RandomAccessFile

<<interface>> DataOutput

<<interface>> DataInput Object

Page 57: Curs Aplicatii distribuite

Curs 4

Partea I – I/O Streams Java – Serializare

Ce se salveaza si se restaureaza in procesul de serializare?� Campurile non-statice? Campurile statice?� Campurile transiente?� Membrii(campuri si metode) privati sau publici?� Protototipul si corpul metodelor? Prototipul metodelor?

Page 58: Curs Aplicatii distribuite

Curs 4

Partea II – Java Native Interface – JNI

Care este utilitatea JNI?

Cand se recomanda programarea JNI?

Care sunt avantajele utilizarii JNI?

Care sunt dezavantajele utilizarii JNI?

Page 59: Curs Aplicatii distribuite

AGENDA Curs 5

Partea I – Exceptii

Partea II – Design Patterns – Singleton classes+Factory methods

Partea III – Muti-threading – Concurenta

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 60: Curs Aplicatii distribuite

Curs 5

Partea I – Exceptii – Mod de propagare

Page 61: Curs Aplicatii distribuite

Curs 5

Partea I – Exceptii - TipuriTipuri de exceptii:1.checked exception (exceptii verificate) = NU trec de compilare. Se poate prevede mecanism de “recovery”. Musai mecanism try-catch.

2.errors (erori) = trec de compilare DAR nu se poate prevedea functionarea defectuasa (e fizic stricat hard-diskul si la deschiderea de fisier se arunca ‘java.io.IOError’). De obicei nu exista mecanism de try-catch.

3.runtime exception (exceptii la rulare) = trec de compilare DAR din cauza logicii de la dezvoltare defectuase rezulta din calcule numitor=0 si mai departe o impartire la 0. Se poate utiliza try-catch, dar mai bine se elimina bug-ul de reuseste ca din calcule sa rezulte numitor=0.

•2+3 = unchecked exception

Page 62: Curs Aplicatii distribuite

Curs 5

Partea I – Exceptii – ierarhie de clase

Page 63: Curs Aplicatii distribuite

Curs 5

Partea I – Exceptii – C vs Java

Page 64: Curs Aplicatii distribuite

Curs 5

Partea II – Clase Singleton & Factory Methods

Care este utilitatea claselor Singleton?

Care este modalitatea dezvoltarii a claselor Singleton?

Care este utilitatea metodelor factory?

Cum se pot dezvolta metode factory?

Page 65: Curs Aplicatii distribuite

Curs 5

Partea III – Multi-threading

Incrementarea unei variabile este operati atomica?

Sunt avantaje/dezavantaje pentru procesare multi-fir pe un procesor?

Sunt avantaje/dezavantaje pentru procesare multi-fir pe un multi-procesor?

Care este diferenenta intre procesare multi-fir si multi-proces?

Page 66: Curs Aplicatii distribuite

Curs 5

Partea III – Multi-threading

Page 67: Curs Aplicatii distribuite

Curs 5

Partea III – Multi-threadingMutexes are used to prevent data inconsistencies due to race conditions.

A race condition often occurs when two or more threads need to perform operations on the same memory area, but the results of computations depends on the order in which these operations are performed.

Mutexes are used for serializing shared resources. Anytime a global resource is accessed by more than one thread the resource should have a Mutex associated with it.

One can apply a mutex to protect a segment of memory ("critical region") from other threads.

Mutexes can be applied only to threads in a single process and do not work between processes as do semaphores.

In Java Mutex is quite � synchronized

Page 68: Curs Aplicatii distribuite

Curs 5

Partea III – Multi-threading

Page 69: Curs Aplicatii distribuite

Curs 5

Partea III – Multi-threading

Page 70: Curs Aplicatii distribuite

Curs 5

Partea III – Multi-threading – Concurenta

Page 71: Curs Aplicatii distribuite

AGENDA Curs 6

Partea I – Muti-threading – Cooperare/Producator-Consumator

Partea II – Stiva de protocoale TCP/IP – IP, UDP, TCP

Partea III – Java Socket

Partea IV – Studiu de caz R1 => IP,UDP,SNMP + ASN1.DER

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 72: Curs Aplicatii distribuite

Curs 6

Partea I – Multi-threading - ProducatorConsumator.java

Page 73: Curs Aplicatii distribuite

Curs 6

Partea I – Multi-threading – Cooperare

Page 74: Curs Aplicatii distribuite

Curs 6

Partea I – Multi-threading – Cooperare

Page 75: Curs Aplicatii distribuite

Curs 6

Partea I – Multi-threading – Cooperare

Page 76: Curs Aplicatii distribuite

Curs 6

Partea I – Multi-threading

De ce se poate utiliza “synchronized la nivel de metoda in mod consistent”doar in interiorul claselor care nu sunt derivate din Thread sau nuimplementeaza interfata Runnable?

Java MUTEX � synchronized * poate fi folosit la nivel de metoda daca sinumai daca metoda face parte dintr-o clasa care NU este derivata din Thread(implementeaza Runnable)

Care e diferenta intre semafor si variabile mutex?

Ce obiecte/instante sunt thread-safe? – immutable, singleton, “normale”, “finale”?

Page 77: Curs Aplicatii distribuite

Curs 6 – SECTIUNEA 2

Partea II – Stiva de protocoale TCP/IP

Page 78: Curs Aplicatii distribuite

Curs 6

Partea II – Incapsulare + Multiplexare/Demultiplexare

Page 79: Curs Aplicatii distribuite

Curs 6

Partea II – Multiplexare/Demultiplexare

Page 80: Curs Aplicatii distribuite

Curs 6

Partea II – IP – RFC 791 – Submasking+Rutare+NAT

Physical Level

IEEE 802.3

Ethernet CSMA/CD

IEEE 802.11 IEEE 802.16

WiFi WiMAX

IEEE 802.5

Token Ring

IEEE 802.6

DQDB

Level Data connection

IEEE 802

Page 81: Curs Aplicatii distribuite

Curs 6

Partea II –TCP – RFC 793 – Orientat Conexiune

Cum realizeaza TCP orientarea pe conexiune?

Page 82: Curs Aplicatii distribuite

Curs 6

Partea II –TCP – RFC 793

Page 83: Curs Aplicatii distribuite

Curs 6

Partea II – UDP – RFC 768 – Neorientat Conexiune

Page 84: Curs Aplicatii distribuite

Curs 6

Partea III – C vs Java Socket – UDP

Page 85: Curs Aplicatii distribuite

Curs 6

Partea III – Java Socket – UDP

UDPServer

Page 86: Curs Aplicatii distribuite

Curs 6

Partea III – Java Socket – UDP

UDPClient

Page 87: Curs Aplicatii distribuite

Curs 6

Partea III – C Socket – TCP

Page 88: Curs Aplicatii distribuite

Curs 6

Partea III – Java Socket – TCP

import java.net.*;

TCPServer/Client

Page 89: Curs Aplicatii distribuite

Curs 6

Partea III – Java Socket – TCP

TCPServer

Page 90: Curs Aplicatii distribuite

Curs 6

Partea III – Java Socket – TCP

TCPServer

Page 91: Curs Aplicatii distribuite

Curs 6

Partea III – Java Socket – TCP

TCPClient

Page 92: Curs Aplicatii distribuite

Curs 6

Partea III – Java Socket – TCP

TCPClient

Page 93: Curs Aplicatii distribuite

Curs 6

Partea IV – SNMP – RFC 1157

Page 94: Curs Aplicatii distribuite

Curs 6

Partea IV – ASN.1

Page 95: Curs Aplicatii distribuite

Curs 6

Partea IV – ASN.1

Page 96: Curs Aplicatii distribuite

Curs 6

Partea IV – ASN.1 – TLV

Page 97: Curs Aplicatii distribuite

Curs 6

Partea IV – ASN.1 DER – TLV

Page 98: Curs Aplicatii distribuite

Curs 6

Partea IV – ASN.1 - OID

http://www.oid-info.com/cgi-bin/display

Page 99: Curs Aplicatii distribuite

Curs 6

Partea IV – ASN.1 - OID

1.2.840.113549.1.1.5 ({iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-1(1) sha1-with-rsa-signature(5)})

Page 100: Curs Aplicatii distribuite

Curs 6

Partea IV – ASN.1 - OID

Page 101: Curs Aplicatii distribuite

Curs 6

Partea IV – SNMP – RFC 1157

Page 102: Curs Aplicatii distribuite

Curs 6

Partea IV – SNMP – RFC 1157

Page 103: Curs Aplicatii distribuite

Curs 6

Partea IV – SNMP – RFC 1157

Page 104: Curs Aplicatii distribuite

Curs 6

Partea IV – SNMP – RFC 1157

Page 105: Curs Aplicatii distribuite

Curs 6

Partea IV – SNMP – RFC 1157

Pentru o intelegere mai buna se consulta ASN.1

Page 106: Curs Aplicatii distribuite

AGENDA Curs 7

Partea I – Stiva de protocoale TCP/IP – IP, UDP, TCP – continuare

Partea II – Java Socket – continuare multi-threading

Partea III – Studiu de caz R2 => IP,TCP,SMTP + BASE64

Partea IV – Studiu de caz R3 => IP, TCP, HTTP+ MIME - seminar

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 107: Curs Aplicatii distribuite

Curs 7

Partea I – UDP – RFC 768 – Neorientat Conexiune

Page 108: Curs Aplicatii distribuite

Curs 7

Partea I –TCP – RFC 793 – Orientat Conexiune

Cum realizeaza TCP orientarea pe conexiune?

Page 109: Curs Aplicatii distribuite

Curs 7

Partea I –TCP – RFC 793

Page 110: Curs Aplicatii distribuite

Curs 7

Partea II – Socket – continuare multi-threading

� Java Multithreading UDP Client & Server1

� Java Real Multithreading UDP Client & Server2

� Java Simple Multi-threading TCP Client & Server

Page 111: Curs Aplicatii distribuite

Curs 7

Partea II – C Socket – TCP

Page 112: Curs Aplicatii distribuite

Curs 7

Partea III – SMTP – RFC 2821

Page 113: Curs Aplicatii distribuite

Curs 7

Partea III – SMTP – RFC 2821

Page 114: Curs Aplicatii distribuite

Curs 7

Partea III – Base64

Base64 encoding is used in practice usually for transport over the network and heterogeneous environments binary code such as pictures or executable code. The techniques is very simple: to transform each 3 bytes values into 4 bytes value in order to avoid to obtain values greater then 127 per byte.

For instance, if the scope is to encode the word “Man” into Base64 encoding then it is encoded as “TWFu”. Encoded in ASCII (in ISO 8859-1, one value per byte), M, a, n are stored as the bytes 77 (0x4D), 97 (0x61), 110 (0x6E), which are 01001101, 01100001, 01101110 in base 2.

Page 115: Curs Aplicatii distribuite

Curs 7

Partea III – Base64

Page 116: Curs Aplicatii distribuite

Curs 7

Partea III – SMTP – RFC 2821

Page 117: Curs Aplicatii distribuite

Curs 7

Partea III – SMTP – RFC 2821

Page 118: Curs Aplicatii distribuite

Curs 7

Partea III – SMTP – RFC 2821

Page 119: Curs Aplicatii distribuite

Curs 7

Partea III – SMTP – RFC 2821

Page 120: Curs Aplicatii distribuite

Curs 7

Partea III – SMTP – RFC 2821

Page 121: Curs Aplicatii distribuite

Curs 7

Partea III – SMTP – RFC 2821

Page 122: Curs Aplicatii distribuite

Curs 7

Partea IV – HTTP – Server HTTP

Page 123: Curs Aplicatii distribuite

AGENDA Curs 8

Partea I – Studiu de caz R4 => IP,TCP,HTTP – URLConnection Client

Partea II – Studiu de caz R5 => IP,TCP,FTP

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 124: Curs Aplicatii distribuite

Curs 8

Partea I – HTTP – RFC 2616

Page 125: Curs Aplicatii distribuite

Curs 8

Partea I – HTTP – RFC 2616

Page 126: Curs Aplicatii distribuite

Curs 8

Partea I – HTTP – URLConnection client

Page 127: Curs Aplicatii distribuite

Curs 8

Partea II – FTP – RFC 959

Page 128: Curs Aplicatii distribuite

Curs 8

Partea II – FTP – RFC 959

Page 129: Curs Aplicatii distribuite

Curs 8

Partea II – FTP – RFC 959 – Server FTP

� Server.java� ServerPI.java� ServerDTP.java

Page 130: Curs Aplicatii distribuite

Curs 8

Partea II – FTP – Server FTP

Page 131: Curs Aplicatii distribuite

Curs 8

Partea II – FTP – Server FTP

In order to use active mode, the client sends a PORT command, with the IP and port as argument.

The format for the IP and port is "h1,h2,h3,h4,p1,p2".

Each field is a decimal representation of 8 bits of the host IP, followed by the chosen data port.

For example, the client with an IP of 192.168.0.5, listening on port 5001 for the data connection will send the command "PORT 192,168,0,5,19,137".

The port fields should be interpreted as p1×256 + p2 = port, or, in this example, 19*256 + 137 = 5001

The FTP client will be TCP server in port 5001 and the FTP server became TCP client from port 20

Page 132: Curs Aplicatii distribuite

Curs 8

Partea II – FTP – Server FTP

Page 133: Curs Aplicatii distribuite

Curs 8

Partea II – FTP – Server FTP

Page 134: Curs Aplicatii distribuite

Curs 8

Partea II – FTP – Server FTP

Page 135: Curs Aplicatii distribuite

Curs 8

Partea II – FTP – Server FTP

Page 136: Curs Aplicatii distribuite

Curs 8

Partea II – FTP – Server FTP

In passive mode, the FTP server opens a dynamic port (49152–65535), sends the FTP client the server's IP address to connect to and the port on which it is listening (a 16 bit value broken into a high and low byte, like explained before) over the control stream and waits for a connection from the FTP client.

In this case the FTP client binds the source port of the connection to a dynamic port between 49152 and 65535.

To use passive mode, the client sends the PASV command to which the server would reply with something similar to "227 Entering Passive Mode(127,0,0,1,192,52)". The syntax of the IP address and port are the same as for the argument to the PORT command. HERE server port is 49204.

In extended passive mode, the FTP server operates exactly the same as passive mode, however it only transmits the port number (not broken into high and low bytes) and the client is to assume that it connects to the same IP address that was originally connected to. Extended passive mode was added by RFC 2428 in September 1998.

Page 137: Curs Aplicatii distribuite

Curs 8

Q&A

SNMP – www.snmp4j.org SMTP – java.mail.*;POP3IMAP4

� Elemente necesare invatarii sectiunii 2 – Programarea protocoalelor de retea:� Cod sursa JAVA – Curs + Seminar – http://acs.ase.ro, � Standardele si protocoalele de retea – RFCs + Cursuri, � Analizor de trafic – WireShark - http://ism.ase.ro/temp/networking.zip

� Avem nevoie de SNMP in programarea aplicatiilor distribuite? Avem nevoie de SMTP/POP3/IMAP4 in programarea aplicatiilor distribuite? Avem nevoie de FTP si HTTP?

� Care sunt avantajele/dezavantajele obtinute din “reinventarea rotii” cand existain piata librarii standard sau nonstandard?

Page 138: Curs Aplicatii distribuite

Curs 8

Q&A

Elemente asimilate din programarea protocoalelor de retea:

� Modelul de dezvoltare client/server � Schimbul de mesaje cerere/raspuns – clientul cere informatii

sau servicii iar serverul raspunde� Socket orientat pe conexiune si neorientat pe conexiune –

transfer fiabil vs. nefiabil – TCP vs UDP� Formatul mesajelor – headere si informatie utila – overload vs.

payload� Protocoale si servere cu stare si fara stare – stateful vs.

stateless� Protocoale si schimb de mesaje sincron si asincron – apel de

functii call-back din retea� Securitatea comunicatiei dintre server si client nu este inclusa in

acest curs din motive de timp si curricula.

Page 139: Curs Aplicatii distribuite

AGENDA Curs 9

SECTIUNEA III – Programare web orientata obiect in JEE

Partea I – Tehnologia Java Servlet + Exemple

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 140: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet

Sun: Java Servlet technology provides Web developers with a simple, consistent mechanism for extending the functionality of a Web server and for accessing existing business systems.

WiKi: Servlets are Java programming language objects that dynamically process requests and construct responses. The Java Servlet API allows a software developer to add dynamic content to a Web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML.

Serverul web de teste pentru cursul 8 si 9 este Apache Tomcat 6.0.16http://tomcat.apache.org

Page 141: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet* Java Servlets Intro & Development Cycle

- Structura de baza Java Servlet

- Un Java Servlet care genereaza “Plain Text”

- Compilare si apel Java Servlet

- A Simple Servlet Generating HTML

* Processing the Request: Form Data

- Introduction (Format, URL-encoding, GET, POST)

- Example: Reading Specific Parameters

- Example: Making Table of All Parameters

Page 142: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet* Procesarea cereri HTTP: HTTP Request Headers

- Common Request Headers- Exemplu: Java Servlet pentru afisarea in tabel HTML a Request Headers

* Generarea raspunsului HTTP: HTTP Status Codes & HTTP Response Headers- Overview: Status Codes si Response Headers- Setarea Status Codes din Java Servlets- Setarea Response Headers din Java Servlets- Exemplu: refresh la fiecare 3 secunde prin Response Headers

* Handling Cookies- Cookies Intro- Java Servlet Cookie API- Exemplu: Set/Get Cookie pentru Internet Explorer & Mozilla

* Session Tracking- Session Tracking Overview- Java Servlet Session Tracking API + Exemplu

Page 143: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet

Page 144: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet

Page 145: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet

Page 146: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet

Page 147: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet – Request Header

Page 148: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet – Request Header

Page 149: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet – Response Codes & Err

Page 150: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet - Response Codes

Page 151: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet – Response Headers

Page 152: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet – Cookie & Session Tracking

Apar foarte multe probleme la protocolul HTTP deoarece este un protocol “fara stare” – "stateless"

Tipic aceste probleme pot fi rezolvate prin:

1. Cookies. Cel mai des mod utilizat pentru stocarea informatiilor la server a masini client. Datele nu circula prin internet ci se stocheaza la serverul de Web.

2. URL Rewriting. La fiecare cerere HTTP se ataseaza la sfarsitul URL-ului un sir de caractere unic generat de fiecare data de serverul web.

3. Hidden form fields. Se pot utiliza taguri de genul: <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">

Page 153: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet – Cookie & Session Tracking //create cookie 1 - implicit value in seconds of cookie is within the sessionCookie userCookie = new Cookie("CookieGigel", "CucuBau");response.addCookie(userCookie);

//create cookie 2 - is per yearCookie userCookie2 = new Cookie("CookieIon", "IONIONION");userCookie2.setMaxAge(SECONDS_PER_YEAR); response.addCookie(userCookie2);

Cookie[] cookies = request.getCookies();if (cookies != null) {

for(int i=0; i<cookies.length; i++) {Cookie cookie = cookies[i];if ("CookieGigel".equals(cookie.getName())) {…

Page 154: Curs Aplicatii distribuite

Curs 9

Partea I – Java Servlet – Cookie & Session Tracking public void processRequest(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException {

HttpSession session = request.getSession(true);response.setContentType("text/html");PrintWriter out = response.getWriter();String title = "Show Session"; String heading;Integer accessCount = new Integer(0);if (session.isNew()) {heading = "Welcome, Newcomer";

} else {heading = "Welcome Back";Integer oldAccessCount =(Integer)session.getAttribute("accessCount");if (oldAccessCount != null) {accessCount = new Integer(oldAccessCount.intValue() + 1);

}}

session.setAttribute("accessCount", ""+accessCount);

Page 155: Curs Aplicatii distribuite

AGENDA Curs 10

SECTIUNEA III – Programare web orientata obiect in J EE

Partea I – Tehnologia JSP – Java Server Pages + Taglibs + Exemple*AJAX si MVC ca Java Struts, Spring, JSF nu fac obiectul acestui curs

SECTIUNEA IV – Programare distribuita orientata pe a peluri la distanta, componente si servicii in JEE

Partea II – Tehnologia JRMI – Java Remote Method Invocation + Exemple

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 156: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

� Necesitatea si arhitectura JSP

� Ciclul de viata JSP

� Sinteza sintaxa JSP + Directive + DEMO

� Variabile predefinite JSP

� Actiuni predefinite JSP

� DEMO JSP si JSPX

Page 157: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

Necesitatea tehnologiei JSP

Cu tehnologia Java Servlet se realiza usor:– Preluarea datelor din formular– Preluarea header-elor din cererea HTTP– Setarea header-elor si a codurilor de stare din raspunsul HTTP– Utilizarea “cookies” si “session tracking” – protocol cu stare– Partajarea datelor intre servleti

Cu tehnologia Java Servlet se realiza destul de greu:– Generarea codului HTML utilizant metoda “println” din clasa PrintWriter– Mentenanta codului HTML generat

Page 158: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

Idei:– Utilizarea codului HTML standard in majoritatea paginilor– Intreaga pagina JSP este translatata in Java servlet (o singura data, la primulapel), si servletul generat este invocat de fiecare data pentru fiecare cerere HTTP

• Exemplu:

<!DOCTYPE …><HTML><HEAD><TITLE>Order Confirmation</TITLE><LINK REL=STYLESHEET HREF="JSP-Styles.css“ TYPE="tex t/css"></HEAD><BODY><H2>Order Confirmation</H2>Thanks for ordering <I> <%= request.getParameter("title") %> </I></BODY></HTML>

Page 159: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

Page 160: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

Lifecycle JSP

Page 161: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

Exemplu – DEMO – test01.jsp:Desi in Java Servlet se poate face orice ce se poate face in JSP (pentru ca JSP este Java Servlet) se recomanda JSP deoarece:– Se scrie mai usor cod HTML– Se depaneaza si mentine mai usor codul HTML– Nu se seteaza variable de mediu si pur si simplu se copiaza in director web

Page 162: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

Page 163: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

Page 164: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

Page 165: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

Page 166: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

Page 167: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

VARIABILE – OBIECTE predefinite in JSP

Pentru a simplifica codul in expresii si scriptlet-uri JSP exista 8 obiecte – variabileimplicite.

1 request

This is the HttpServletRequest associated with the request, and lets you look at the request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies, Referer, etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest other than HttpServletRequest, if the protocol in the request is something other than HTTP. This is almost never done in practice.

2 response

This is the HttpServletResponse associated with the response to the client. Note that, since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servletsonce any output has been sent to the client.

Page 168: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

3 out

This is the PrintWriter used to send output to the client. However, in order to make the response object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter. Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. This was discussed in Section 5. Also note that out is used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream, and thus rarely need to refer to out explicitly.

4 session

This is the HttpSession object associated with the request. Recall that sessions are created automatically, so this variable is bound even if there was no incoming session reference. The one exception is if you use the session attribute of the page directive (see Section 5) to turn sessions off, in which case attempts to reference the session variable cause errors at the time the JSP page is translated into a servlet.

Page 169: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

5 application

This is the ServletContext as obtained via getServletConfig().getContext().

6 config

This is the ServletConfig object for this page.

7 pageContext

JSP introduced a new class called PageContext to encapsulate use of server-specific features like higher performance JspWriters. The idea is that, if you access them through this class rather than directly, your code will still run on "regular" servlet/JSP engines. It is used also for Java Bean synchronization and session tracking info storage for not allocating more beans for one page session.

8 page

This is simply a synonym for this, and is not very useful in Java. It was created as a placeholder for the time when the scripting language could be something other than Java.

Page 170: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages

ACTIUNI in JSP

Actiunile in JSP utilizeaza constructii XML pentru a controla comportamentul unuicontainer de Java Servlet. Utilizand actiunile JSP se pot insera dinamic fisiere, reutiliza componente JavaBeans (inclusiv cele care se conecteaza la baze de date), redirecta utilizatorul catre alte pagini web, sau genera HTML ce contine obiecte Java Applet.

� jsp:include - Include un fisier in timpul in care pagina este ceruta.

� jsp:useBean – Gaseste sau instantiaza un JavaBean – componenta Java.

� jsp:setProperty – Seteaza propietatea unui JavaBean.

� jsp:getProperty – Insereaza propietatea unui JavaBean in raspuns-output.

� jsp:forward - Redirecteaza o cerere catre o noua pagina.

� jsp:plugin - Genereaza cod browser-specific care creaza un tag OBJECT sauEMBED pentru aplicatii Java care ruleaza la client – Java Applet.

Page 171: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages – DEMO

In JEE:

Annotations-Reflection + (Taglibs + Generics + Servlet/JSP) �MVC + EJB + JMS + Rules Engine/BPM-BPEL = LOVE

Page 172: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages – DEMO Taglibs

http://jakarta.apache.org/taglibs/doc/standard-doc/intro.html

Using JSTL: JSTL includes a wide variety of tags that fit into discrete functional areas. To reflect this, as well as to give each area its own namespace, JSTL is exposed as multiple tag libraries. The URIs for the libraries are as follows:

Core: http://java.sun.com/jsp/jstl/core

XML: http://java.sun.com/jsp/jstl/xml

Internationalization: http://java.sun.com/jsp/jstl/fmt

SQL: http://java.sun.com/jsp/jstl/sql

Functions: http://java.sun.com/jsp/jstl/functions

Page 173: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages – DEMO Taglibs

Page 174: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages – DEMO Taglibs

Page 175: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages – DEMO Taglibs

Page 176: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages – DEMO Struts MVC

1. Java Struts/Struts 22. Java Spring/Spring 23. JSF – Java Server Faces

Page 177: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages – DEMO Struts MVC

Page 178: Curs Aplicatii distribuite

Curs 10

Partea I – JSP – Java Server Pages – DEMO Struts MVC1. User clicks on a link in an HTML page.

2. Servlet controller receives the request, looks up mapping information in struts-config.xml, and routes to an action.

3. Action makes a call to a Model layer service.

4. Service makes a call to the Data layer (database) and the requested data is returned.

5. Service returns to the action.

6. Action forwards to a View resource (JSP page)

7. Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP page.8. JSP file is invoked and sent to the browser as HTML.9. User is presented with a new HTML page in a web browser.

Page 179: Curs Aplicatii distribuite

Curs 10

Partea II – JRMI – Java Remote Method Invocation

• RMI Overview• Java RMI permite programatorilor sa execute functii/metode dintr-o

clasa din alta masina virtuala/masina ca si cum ar fi in aceeasi masinavirtuala. Local Machine (Client)

SampleServerInterfaceremoteObject;

int s;…

s = remoteObject.sum(1,2);

System.out.println(s);

Remote Machine (Server)

public int sum(int a,int b) {return a + b;

}

1,2

3

SECTIUNEA IV – Programare distribuita orientata pe a peluri la distanta, componente si servicii in JEE

Page 180: Curs Aplicatii distribuite

Curs 10

Partea II – JRMI – Java Remote Method Invocation

Arhitectura RMI

• RMI Server trebuie sa-si inregistrezenumele si adresa unde ruleaza in Registry – bind

• RMI Client cauta numele si adresaserverului RMI in Registry – lookup

• RMI Stub serializeaza si secventializeaza– “marshalling” parametrii catre RMI Skeleton. RMI Skeleton deserializeaza sidesecventieaza parametrii primiti –“unmarshalling”. Apoi RMI Skeleton apeleaza metoda si trimite raspunsulinapoi la RMI Stub prin “marshalling”.

Page 181: Curs Aplicatii distribuite

Curs 10

Partea II – JRMI – Java Remote Method Invocation

JRMI Stub & Skeleton

• Un client invoca o metoda la distanta dupa ce a obtinut referinta catreobiectul server prin JRMI registry de la server. Apelul metodei este transmiscatre JRMI Stub.

• JRMI Stub este responsabil pentru apelul metodei, transmitereaparametrilor care JRMI Skeleton de la server si preluarea raspunsului de la JCRMI Skeleton de la server

• JCRMI Stub deschide socket la server, “marshaling” obiectele serializabileparametrii la server si redirecteaza fluxul de date catre JCRMI Skeleton.

• JCRMI Skeleton contine o metoda ce primeste apelurile la distanta, “unmarshaling” obiectele parametrii, si apeleaza implementarea metodei de la JCRMI server

Stu

b

RMI Client RMI Serverskeleton

return

call

Page 182: Curs Aplicatii distribuite

Developing RMI System*in fisierul readme.txt:DEZVOLTARE SERVER JRMI:1. Definirea interfetei la distanta – remote interface2. Dezvoltarea clasei Java pentru generarea obiectului la distanta – JRMI

server object – prin implementarea interfetei de la pasul 1.3. Dezvoltarea programului principal server4. Compilarea fisierelor server si apoi generarea JCRMI Skeleton si

JCRMI StubDEZVOLTARE CLIENT JRMI:5. Dezvoltarea programului client6. Copierea fisierelor bytecode JCRMI Stub si interfata la distanta de la

server la client7. Compilarea surselor Java ale clientului alaturi de fisierele de la pasul 6.RULARE SERVER JRMI:8. Start program JRMI registry.9. Start program server.RULARE CLIENT JRMI:10.Start program client

Curs 10

Partea II – JRMI – Java Remote Method Invocation

Page 183: Curs Aplicatii distribuite

Pas 1: Definirea interfetei la distanta

• Remote interface between the client and server objects.

/* SampleServerInterface.java */

import java.rmi.*;

public interface SampleServerInterface extends Remote

{

public int sum(int a,int b) throws RemoteException;

}

Curs 10

Partea II – JRMI – Java Remote Method Invocation

Page 184: Curs Aplicatii distribuite

Pas 2: Dezvoltarea obiectului la distanta prin dezvoltarea clasei Java si implementarea interfetei

• JRMI obiect server este un “unicast remote server” => derivarea din clasajava.rmi.server.UnicastRemoteObject .

• JRMI obiect server implementeaza interfata de la pasul 1

/* SampleServerImpl.java */

import java.rmi.*;

import java.rmi.server.*;

import java.rmi.registry.*;

public class SampleServerImpl extends UnicastRemoteObject

implements SampleServerInterface {

SampleServerImpl() throws RemoteException

{ super(); }

Curs 10

Partea II – JRMI – Java Remote Method Invocation

Page 185: Curs Aplicatii distribuite

• JRMI obiect server implementeaza metodele la distanta din interfata de la pasul 1

/* SampleServerImpl.java */

public int sum(int a,int b) throws RemoteException

{

return a + b;

}

}

Curs 10

Partea II – JRMI – Java Remote Method Invocation Pas 2: Dezvoltarea obiectului la distanta prin

implementarea interfetei

Page 186: Curs Aplicatii distribuite

Pas 3: Dezvoltarea programului principal server

Curs 10

Partea II – JRMI – Java Remote Method Invocation

Programul principal JRMI server creaza, instaleaza si utilizeazaRMISecurityManager pentru a-si proteja resursele proprii in timpulcomunicatiei cu JRMI clienti si pentru a-si expune doar partile specificate in fisierul java.policy.

Programul principal server creaza obiectul server JRMI – JRMI server object din clasa creata la pasul 2 si care implementeaza interfata de la pasul 1

Serverul JRMI trebuie sa-si inregistreze obiectul server prin asocierea unuinume in aplicatia JRMI registry – bind() sau rebind() .

Page 187: Curs Aplicatii distribuite

Pas 3: Dezvoltarea programului principal server/* SampleServerProgMain.java */

public static void main(String args[]){

try{

System.setSecurityManager(new RMISecurityManager()) ;//set the security manager

//create a local instance of the JRMI server objectSampleServerImpl Server = new SampleServerImpl();

//put the local instance in the registryNaming.rebind("rmi://localhost:1099/SAMPLE-SERVER" , Server);

...

Curs 10

Partea II – JRMI – Java Remote Method Invocation

Page 188: Curs Aplicatii distribuite

Pas 5: Dezvoltarea programului client• Programul principal JRMI client creaza, instaleaza si utilizeaza RMISecurityManager

pentru a-si expune catre JRMI server doar partile specificate in fisierul java.policy

• Pentru ca un obiect client sa invoce o metoda la distanta a unui obiect server JRMI, mai intai trebuie sa obtina o referinta la obiectul server de la distanta. Clientii JRMI primesc referinta obiectului server dupa ce interogheaza aplicatia JRMI registry prinlookup() din clasa java.rmi.Naming .

• Numele obiectului server JRMI se specifica intr-un URL de forma: (rmi://server_registry_host:port/server_rmi_name)–(rmi://127.0.0.1:1099/SAMPLE-

SERVER)• Portul predefinit pentru interogarea aplicatiei RMI registry este 1099.• Numele specificat in URL “server_rmi_name” trebuie sa fie acelasi nume pe care l-a

utilizat serverul pentru inregistrarea obiectului server RMI in aplicatia RMI registry. In acest examplu, numele este “SAMPLE-SERVER”

• Apelul metodei la distanta server se face utilizand un obiect client de tipul claseiinterfata (remoteObject ).

Curs 10

Partea II – JRMI – Java Remote Method Invocation

Page 189: Curs Aplicatii distribuite

import java.rmi.*;

import java.rmi.server.*;

public class SampleClient

{

public static void main(String[] args)

{

// set the security manager for the client

System.setSecurityManager(new RMISecurityManager()) ;

//get the remote object from the registry

try

{

System.out.println("Security Manager loaded");

String url = “rmi://localhost:1099/SAMPLE-SERVER" ;

SampleServerInterface remoteObject =

(SampleServer)Naming.lookup(url) ;

System.out.println("Got remote object");

System.out.println(" 1 + 2 = " + remoteObject.sum(1,2) );

}

catch (RemoteException exc) {

...

Pas 5: Dezvoltarea programului client

Page 190: Curs Aplicatii distribuite

Java Policy File – java.policy

• In Java, o aplicatie actioneaza in functie de privilegiile cerute de interpretorul java.exe catre sistemul de operare in baza unui fisier de politici de securitate. De obicei este in %JAVA_HOME%/jre/lib/security:

grant {

permission java.security.AllPermission;

};

• Un exemplu modificat de permisiuni:grant {

permission java.io.filePermission “d:/*”, “read”, “write”;

permission java.net.SocketPermission “somehost.somedomain.com:999”,”connect”;

permission java.net.SocketPermission “*:1024-65535”,”connect,request”;

permission java.net.SocketPermission “*:80”,”connect”;

};

Curs 10

Partea II – JRMI – Java Remote Method Invocation

Page 191: Curs Aplicatii distribuite

Cometarii asupra fisierului Java Policy

1. permite claselor Java sa citeasca si sa scrie fisiere doar in directorul “d:/tmp” si subdirectoarele sale

2. permite claselor Java sa stabileasca conexiuni de retea cu computerul “somehost.somedomain.com” catre portul 999 a serverului

3. permite claselor Java sa accepte conexiuni si cereri de la oricecomputer pe porturile de retea mai mari de 1024

4. permite claselor Java sa stabileasca conexiuni de retea catreorice computer utilizand portul 80 a serverului, oricare ar fi el –pentru aplicatii HTTP.

Curs 10

Partea II – JRMI – Java Remote Method Invocation

Page 192: Curs Aplicatii distribuite

Curs 10

Partea II – JRMI – Java Remote Method Invocation

1. Configurat firewall atat la client cat si la server

2. Configurat fisier java.policy atat la client cat si la server

3. Rulat aplicatiile tinand cont de fisierul de politica de securitate java.policy si de eventualeredimensionari heap a masini virtuale Java – -Xms1000000000

Elemente necesare pentru rularea aplicatiilor JRMI

Page 193: Curs Aplicatii distribuite

AGENDA Curs 11

SECTIUNEA IV – Programare distribuita orientata pe a peluri la distanta, componente si servicii in JEE

Partea I – Tehnologia CORBA – Java IDL + Exemple

Partea II – Web Services – SOAP

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 194: Curs Aplicatii distribuite

Curs 11

Partea I – CORBA

OMG created CORBA. CORBA loves JAVA.1. CORBA Basic Architecture2. CORBA Basic Flow3. ORB – Object Request Broker4. GIOP vs IIOP, IOR5. IDL is CORBA “language independency”6. CORBA Services7. Products – SUN Java IDL

Page 195: Curs Aplicatii distribuite

Curs 11

Partea I – CORBA – Basic Architecture

IIOPORB

Client Host Machine

Client Object

ORB

Server Host Machine

Stub

Remote Object

Skeleton

Page 196: Curs Aplicatii distribuite

Curs 11

Partea I – CORBA – Basic Architecture

Stubs and Skeletons

• Stub – lives on client– pretends to be remote object

• Skeleton– lives on server– receives requests from stub– talks to true remote object– delivers response to stub

Similar with RMI 1.1 in concept

Page 197: Curs Aplicatii distribuite

Curs 11

Partea I – CORBA – Basic Architecture

Client Server

ORB ORB

response

“Object Bus”

request

Page 198: Curs Aplicatii distribuite

Copyright © 1997 Alex Chaffee

Client Virtual Machine

Client

Server Virtual Machine

Stub

Remote Object

Skeleton

Name Server Virtual Machine

“Gigel”

Server

Curs 11

Partea I – CORBA Basic Flow without ORB is like RMI

Page 199: Curs Aplicatii distribuite

Copyright © 1997 Alex Chaffee

Client Virtual Machine

Client

Server Virtual Machine

Stub

Remote Object

Skeleton

Name Server Virtual Machine

“Gigel”

Server

Curs 11

Partea I – CORBA Basic Flow without ORB is like RMI

1

2

1. Server Creates Remote Object2. Server Registers Remote Object

Page 200: Curs Aplicatii distribuite

Copyright © 1997 Alex Chaffee

Client Virtual Machine

Client

Server Virtual Machine

Stub

Remote Object

Skeleton

Name Server Virtual Machine

“Gigel”

Server

Curs 11

Partea I – CORBA Basic Flow without ORB is like RMI

4

3. Client requests object from Name Server4. Name Server returns remote reference(and stub gets created)

3

Page 201: Curs Aplicatii distribuite

Copyright © 1997 Alex Chaffee

Client Virtual Machine

Client

Server Virtual Machine

Stub

Remote Object

Skeleton

Name Server Virtual Machine

“Gigel”

Server

Curs 11

Partea I – CORBA Basic Flow without ORB is like RMI

6

5. Client invokes stub method6. Stub talks to skeleton7. Skeleton invokes remote object

method

5 7

Page 202: Curs Aplicatii distribuite

• OMG does not specify exactly where the ORB is in CORBA.

• Depending on which CORBA implementation (product) is used, the ORB may be:– A set of run-time libraries– A server machine/process– Part of the operating system (Spring)– Part of a web browser (Netscape)

Curs 11

Partea I – CORBA – ORB Conceptual

Page 203: Curs Aplicatii distribuite

Curs 11

Partea I – CORBA – ORB in Practice

FEATURES:� Object Request Broker - “Object Bus”� Handles all communication among objects� Each host (machine) has its own ORB� ORBs know how to talk to each other� ORB also provides basic services to client

RESPONSABILITIES:� Find the object implementation for the request� Prepare the object implementation to receive the request� Communicate the data making up the request� Retrieve results of request

Note:� There’s an ORB on the server too, and ORB receives request� ORB is good if Stub and Skeleton are written in different programming language

Page 204: Curs Aplicatii distribuite

• Method invocations– Static and Dynamic– Remote objects or CORBA services

• High-level language bindings– Use your favorite language; ORB translates

• Self-describing– Provides metadata for all objects and services

Curs 11

Partea I – CORBA – ORB Features

Page 205: Curs Aplicatii distribuite

• Local or remote– Same API wherever target object lives

• Preserves context– Distributed security and transactions

• Coexistence with legacy code– Just provide a wrapper object

Curs 11

Partea I – CORBA – ORB Features

Page 206: Curs Aplicatii distribuite

What is an ORB really?

• Not a separate process• Library code that executes in-process• Listens to TCP ports for connections

– One port per local object

• Opens TCP sockets to other objects– N ports per remote machine

Curs 11

Partea I – CORBA – ORB in Practice

Page 207: Curs Aplicatii distribuite

• The OMG agreed protocol for ORB interoperability is called the General Inter-ORB Protocol (GIOP).

• GIOP defines the logical data representation and message formats for communication.

• The OMG defines a realization of GIOP that uses TCP/IP as the transport layer. This specialization is called the Internet Inter-ORB Protocol (IIOP).

Curs 11

Partea I – CORBA – GIOP and IIOP

Page 208: Curs Aplicatii distribuite

Curs 11

Partea I – CORBA – GIOP and IIOP

Page 209: Curs Aplicatii distribuite

Curs 11

Partea I – CORBA – GIOP and IIOP

GIOP Messages:

• Request message contains a complete marshaled invocation request (object reference, name of the method, input parameters)– Each request has request ID

• Reply message contains a marshaled return values and output parameters– Reply message has a corresponding request ID of the request message

Page 210: Curs Aplicatii distribuite

• An IOR (Interoperable Object Reference) is managed internally by the interoperating ORBs.

• An IOR may include:

– ORB's internal object reference– Internet host address

– Port number • It is not necessary for an application

programmer to know the structure of an IOR.

Curs 11

Partea I – CORBA – ORB

Page 211: Curs Aplicatii distribuite

IOR:000000000000001049444c3a466f7274756e653a312e300000IOR:000000000000001049444c3a466f7274756e653a312e300000IOR:000000000000001049444c3a466f7274756e653a312e300000IOR:000000000000001049444c3a466f7274756e653a312e300000

000001000000000000005e00010000000000186d6179666c792000001000000000000005e00010000000000186d6179666c792000001000000000000005e00010000000000186d6179666c792000001000000000000005e00010000000000186d6179666c792

e73642e6d6f6e6173682e6564752e617500070a000000000036e73642e6d6f6e6173682e6564752e617500070a000000000036e73642e6d6f6e6173682e6564752e617500070a000000000036e73642e6d6f6e6173682e6564752e617500070a000000000036

3a5c6d6179666c792e73642e6d6f6e6173682e6564752e617533a5c6d6179666c792e73642e6d6f6e6173682e6564752e617533a5c6d6179666c792e73642e6d6f6e6173682e6564752e617533a5c6d6179666c792e73642e6d6f6e6173682e6564752e61753

a666f7274756e653a466f7274756e65313a3a49523a466f7274a666f7274756e653a466f7274756e65313a3a49523a466f7274a666f7274756e653a466f7274756e65313a3a49523a466f7274a666f7274756e653a466f7274756e65313a3a49523a466f7274

756e65756e65756e65756e65

Curs 11

Partea I – CORBA – ORB

Page 212: Curs Aplicatii distribuite

Pseudo-objects

• The ORB is a pseudo-object• It works just like a remote object, only it’s local

Curs 11

Partea I – CORBA – ORB

The Basic Object Adapter (BOA)

• Another pseudo-object• Helps register objects with the ORB• Functions

– Maintain Implementation Repository– Generate and interpret object references– Activate and deactivate implementation objects– Invoke methods via skeletons

Page 213: Curs Aplicatii distribuite

Why do you need both an ORB and a BOA?

• Allows vendors to optimize or enhance functionality– register many objects en masse– cache object state elsewhere

• E.g. Object database

Curs 11

Partea I – CORBA – ORB

Page 214: Curs Aplicatii distribuite

Using the BOA

• Slightly different procedure for initializing objects• Hides name service from you

– Ask the BOA to register the object– Ask the Helper object to bind the object

• Once the object is created, interface is identical– Just call methods using normal Java syntax

Curs 11

Partea I – CORBA – ORB

Page 215: Curs Aplicatii distribuite

Object Adapters Portable Object Adapter – POA

The POA:• Allows the ORB and Objects to communicate• Provides many services:

– Dispatches client calls to server objects– Handles incoming client calls– Handles registration of servers– Instantiatiates objects at runtime and creates and

manages object references• POA is a BOA – Basic Object Adapter

Curs 11

Partea I – CORBA – ORB

Page 216: Curs Aplicatii distribuite

POA Architecture

• A typical example of the relationship between POA and servants

InvocationORB

POA Manager

POA

Curs 11

Partea I – CORBA – ORB

Page 217: Curs Aplicatii distribuite

Curs 11

Partea I – CORBA – ORB

Page 218: Curs Aplicatii distribuite

Curs 11

Partea I – CORBA – ORB

Page 219: Curs Aplicatii distribuite

• Interface Definition Language• Defines protocol to access objects• Like a contract• Well-specified• Language-independent

Curs 11

Partea I – CORBA use IDL for independency

Page 220: Curs Aplicatii distribuite

Curs 11

Partea I – CORBA use IDL for independency

Page 221: Curs Aplicatii distribuite

//IDL Sample:

module Calc {

interface Adder {

long add(in long x, in long y);

}

}

• Defines an class called Adder which generates objects with a method called “add”

Curs 11

Partea I – CORBA use IDL for independency

Page 222: Curs Aplicatii distribuite

IDL vs. Java vs. C++ conceptsIDL Java C++

module package namespace

interface interface abstract

class

operation method member

function

attribute pair of pair of

methods functions

Curs 11

Partea I – CORBA use IDL for independency

Page 223: Curs Aplicatii distribuite

IDL Modules

• Map to Java packages • Unfortunately, it has the root level name of the mo dule• Clutters up your package hierarchy

Curs 11

Partea I – CORBA use IDL for independency

IDL Interfaces

• Map to Java interfaces

IDL Operations

• Map to Java methods

Page 224: Curs Aplicatii distribuite

IDL Attributes

• Map to pair of functions – like C# do• IDL

– string name;

• Java– public void name(String val);

– public String name();

Curs 11

Partea I – CORBA use IDL for independency

Page 225: Curs Aplicatii distribuite

CORBA Services

• APIs for low-level, common tasks• Life Cycle Service

– creating, copying, moving, removing objects

• Naming Service– Register objects with a name– Look up objects by name

Curs 11

Partea I – CORBA Services

Page 226: Curs Aplicatii distribuite

• Concurrency Control Service– Obtain and release exclusive locks

• Transaction Service– Two-phase commit coordination– Supports nested transactions

• Persistence Service– Storing objects in a variety of databases – RDBMS, OODBMS, file systems

• Security Service– Authentication, ACLs, encryption, etc.

• Event Service– Uncoupled notifications

Curs 11

Partea I – CORBA Services

Page 227: Curs Aplicatii distribuite

• Relationship• Externalization• Query• Licensing• Properties• Time• Trader• Collection• … and so on…

• See what means about CORBA will be never being implemented?

Curs 11

Partea I – CORBA Services

Page 228: Curs Aplicatii distribuite

Remember!• CORBA is a standard by OMG, not an implementation.• There are many implementations in Java and C/C++:

– SUN JDK – Java 2 ORB– VisiBroker for Java or for C++– Orbacus– Orbix– Visigenic(freely available),

• Depending on the particular CORBA implementation, nonstandardized aspects may be different.

Curs 11

Partea I – CORBA Products

Page 229: Curs Aplicatii distribuite

• Should be named “Java CORBA”– More than just IDL

– Full (?) implementation of CORBA in 100% Java

• SUN Java IDL has 3 Parts:– ORB– Naming Service – COS – CORBA Object

Service: tnameserv.exe (Non-persistent) & orbd.exe (Persistent)

– idltojava & javatoidl compiler – now: idlj.exe

• Ships starting with JDK 1.2

Curs 11

Partea I – SUN Java IDL

Page 230: Curs Aplicatii distribuite

The Java ORB

• 100% Java• Generic• Allows Java IDL applications to run either

as stand-alone Java applications, or as applets within Java-enabled browsers

• Uses IIOP

Curs 11

Partea I – SUN Java IDL

Page 231: Curs Aplicatii distribuite

The compiler: Transparent API

• JavaIDL turns IDL into direct method calls• Easy to program• Clients have no knowledge of implementation• Highly portable

Curs 11

Partea I – SUN Java IDL

Page 232: Curs Aplicatii distribuite

The compiler idlj: IDL to Java Mapping

• Defined by OMG and implemented here by SUN

• Translates IDL concepts into Java language constructs

• Everything is accessible by writing normal-looking Java code

Curs 11

Partea I – SUN Java IDL

Page 233: Curs Aplicatii distribuite

The compiler idlj: IDL to Java Type MappingIDL Typebooleanchar / wcharoctetshort / unsigned shortlong / unsigned longlong long / unsigned long longfloatdoublestring / wstring

Java Typebooleancharbyteshortintlong floatdoubleString

Curs 11

Partea I – SUN Java IDL

Page 234: Curs Aplicatii distribuite

The compiler: idlj or idltojava

• Development tool provided by SUN• Automatically generates Java stubs,

skeletons, helpers, holders, ... from IDL• Generates stubs for specific remote

interfaces

Curs 11

Partea I – SUN Java IDL

Page 235: Curs Aplicatii distribuite

Stubs – Client Side

• Java objects call stub methods• Stubs communicate with CORBA objects

– and vice versa• Transparent integration

Skeletons – Server Side

• ORB passes request to skeleton (like a stub)• Skeleton calls local implementation

Curs 11

Partea I – SUN Java IDL

Page 236: Curs Aplicatii distribuite

DEMO – CORBA Server & Client

Remote Interfaces and StubsIDL Interface

StubRemote Object

(Server)Client Skeleton

implements implements

extends

Curs 11

Partea I – SUN Java IDL

Page 237: Curs Aplicatii distribuite

Curs 11

Partea I – CORBA vs RPC/RMI

• Proxy is equivalent to client stub in RPC/RMI; it provides the same object interface as the server object• Proxy marshalls method invocations into messages and unmarshall the reply messages• Skeleton is like a server stub in RPC/RMI

Page 238: Curs Aplicatii distribuite

Curs 11

Partea I – CORBA Advanced Architecture

Object Model• ORB provides few services through ORB interface• Operations to marshall and unmarshall object references• Getting object reference to an object implementing a specific CORBA service

Page 239: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services

1. Web Service Overview2. XML-RPC3. Web Service WSDL4. Web Service SOAP Req & Resp5. Java Web Service Server – Bottom-Up6. Java Web Service Server – Top-Down7. Java Web Service Client – ADB - Top-

Down

Page 240: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services Overview

� "a software system designed to support interoperable Machine to Machine interaction over a network.“ (W3C)� Remote Procedure Call over HTTP

Page 241: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services – XML-RPC

Page 242: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services – XML-RPC� remote procedure calls using HTTP for transport and XML as encoding

� XML-RPC message is an HTTP-POST request

� very simple XML - doesn't use XML namespaces or attributes

� works only with HTTP

Page 243: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services – Products & WSDL

WSDL Concept:

� WSDL – Web Service Definition Language

� WSDL = XML document that describes a web service

� WSDL – Specifies the location of the service and the operations (or methods) it exposes

Web Services Products:

� Apache AXIS2 for Java – course

� SUN Java-WS – integrated in NetBeans 6.0.1 – seminar

Page 244: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services – WSDL

A WSDL describes a web service using the following elements:

� <binding> contains communication protocols used by the web service

� <portType> defines the operations that can be performed by a web service, and the messages that are involved

� <message> defines the in/out messages that are used by the operations ���� methods

� <types> defines data types used by the messages

A WSDL document can also contain extension elements and a <service> elementthat makes it possible to group together the definitions of several web services .

Page 245: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services – SOAP

� SOAP – Simple Object Access Protocol

� simple XML based protocol to let applications excha nge information over HTTP

� defines a format for sending messages

� allows you to get around firewalls (firewalls and p roxy serversnormally block RPC traffic)

� platform and language independent

� transport Protocols: TCP, HTTP, SMTP, and MQ – Messa ge Queues

Page 246: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services – SOAP

A SOAP message is an ordinary XML containing the following elements:

� <Envelope> which identifies that the XML document is a SOAP message

� <Header> which contains application specific information about the SOAP message (such as authentication, payment, etc) .

� <Body> contains the actual SOAP message

� <Fault> contains eventual error messages

Page 247: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services – SOAP with Attachments

� The SOAP messaging protocol allows you to send MIME attachments via SOAP messages. WSDL provides a description of these attachments.

� SOAP with Attachments API for Java (SAAJ) allows you to do XML messaging from the Java platform

� The SAAJ API conforms to the Simple Object Access Protocol (SOAP) 1.1 and 1.2 specifications and the SOAP with Attachments specification.

Page 248: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services – SOAP with Attachments

� The SAAJ API provides the SOAPMessage class to represent a SOAP message.

� SAAJ API also provides the SOAPPart class that is the container for the SOAP-specific portion of a SOAPMessageobject. All messages are required to have a SOAPPart.

�A SOAPPart object is a MIME part and has the MIME headers Content-Id, Content-Location, and Content-Type

SOAP with no attachments

Page 249: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services – SOAP with Attachments

SOAP with two attachments

� A SOAP message may include one or more attachment parts in addition to the SOAP part.

� The SAAJ API provides the AttachmentPart class to represent an attachment part of a SOAP message.

� An attachment part can contain any kind of content.

Page 250: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services - UDDI

� an XML-based registry for businesses worldwide to list themselves on the Internet.

� used in a similar manner to JNDI – to register and l ocate web services

� is a directory for storing information about web services

� is a directory of web service interfaces described by WSDL

Page 251: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services – A Java Architecture

Page 252: Curs Aplicatii distribuite

Curs 11

Partea II – Creating Web Services - BOTTOM-UP - Server

1. set JAVA_HOME, AXIS2_HOME and CATALINA_HOME and all \bin to Path

2. compile java file: javac -cp . package/ServiceName.java

3. create wsdl file: %AXIS2_HOME%/bin/java2wsdl -cp . -cn

package.ServiceName -of ServiceName.wsdl

4. the structure of this service directory will be as follows:

- ServiceName

- META-INF

- services.xml

- ServiceName.wsdl

- lib

- webserv

- ServiceName.class

Page 253: Curs Aplicatii distribuite

Curs 11

Partea II – Creating Web Services - BOTTOM-UP - Server

5. Create service.xml file (set description for service and parameter name)

6. Copy ServiceName directory or ServiceName.aar to: axis2.war/WEB-

INF/services directory in your Servlet engine

7. start the web server

8. Obtain description of the service:

http://localhost:8080/axis2/services/ServiceName?wsdl

http://localhost:8080/axis2/services/ServiceName?xsd

Page 254: Curs Aplicatii distribuite

Curs 11

Partea II – Creating Web Services – TOP-DOWN - Server

1. set JAVA_HOME, AXIS2_HOME and CATALINA_HOME and all \bin to Path

2. create WSDL file for service&create the skeleton for the web service using

the command: %AXIS2_HOME%/bin/WSDL2Java -uri META-

INF/ServiceName.wsdl -p webserv -d adb -s -ss -sd -ssi -o output_directory

3. the following structure of files is generated:

- resources

- services.xml

- ServiceName.wsdl

- src

- webserv

- java files

- build.xml

Page 255: Curs Aplicatii distribuite

Curs 11

Partea II – Creating Web Services – TOP-DOWN - Server

4. modify ServiceNameSkeleton.java by adding code to the methods

5. set AXIS2_CASS_PATH and compile java files:

javac -cp .;%AXIS2_CLASSPATH% package/*.java

� set up the directory structure:

ServiceName

- META-INF

- services.xml

- ServiceName.wsdl

- lib

- package

- class files

- build.xml

Page 256: Curs Aplicatii distribuite

Curs 11

Partea II – Web Services

7. copy ServiceName directory or ServiceName.aar to: axis2.war/WEB-

INF/services directory in your servlet engine and start the server

8. Test the service:

http://localhost:8080/axis2/services/ServiceName?wsdl

http://localhost:8080/axis2/services/ServiceName?xsd

Page 257: Curs Aplicatii distribuite

Curs 11

Partea II – Create Web Services – TOP-DOWN Client

CLIENT types in AXIS 2:

Axis2 Databinding Framework (ADB): ADB is probably the simplest method of

generating an Axis2 client. In most cases, all of the pertinent classes are

created as inner classes of a main stub class. It is not meant to be a full

schema binding application, and has difficulty with structures such as XML

Schema element extensions and restrictions.

XMLBeans: Unlike ADB, XMLBeans is a fully functional schema compiler, so it

doesn't carry the same limitations as ADB. It is, however, a bit more

complicated to use than ADB. It generates a huge number of files, and the

programming model, while being certainly usable, is not as straightforward

as ADB.

Page 258: Curs Aplicatii distribuite

Curs 11

Partea II – Create Web Services – TOP-DOWN Client

CLIENT types in AXIS 2:

JiBX: JiBX is a complete databinding framework that actually provides not only

WSDL-to-Java conversion, but also Java-to-XML conversion. In some ways,

JiBX provides the best of both worlds. JiBX is extremely flexible, enabling you

to choose the classes that represent your entities, but it can be complicated

to set up. On the other hand, once it is set up, actually using the generated

code is as easy as using ADB.

Page 259: Curs Aplicatii distribuite

Curs 11

Partea II – Create Web Services – TOP-DOWN Client

1. Generate client ADB from web service wsdl file using th command:

%AXIS2_HOME%/bin/WSDL2Java -uri ServiceName.wsdl -p clientpackage -d

adb –s

2. compile the stub

javac -cp .;%AXIS2_CLASSPATH% clientpackage/ClientStub.java

3. Compile and run the client

javac -cp .;%AXIS2_CLASSPATH% clientpackage/Client.java

java -cp .;%AXIS2_CLASSPATH% clientpackage/Client.java

Page 260: Curs Aplicatii distribuite

AGENDA Curs 12

SECTIUNEA IV – Programare distribuita orientata pe a peluri la distanta, componente si servicii in JEE

Partea I – JMS – Java Message Service

Partea II – EJB – Enterprise Java Beans

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR DISTRIBUITE

Page 261: Curs Aplicatii distribuite

Curs 12

Partea I – JMS API

Page 262: Curs Aplicatii distribuite

Curs 12

Partea I – JMS Point2Popint vs. Topic

Page 263: Curs Aplicatii distribuite

Curs 12

Partea I – JMS Synchronous vs. Asynchronous

Sun Message Consumption Types:

“Messaging products are inherently asynchronous in that no fundamental timing dependency exists between the production and the consumption of a message. However, the JMS Specification uses this term in a more precise sense. Messages can be consumed in either of two ways:

* Synchronously. A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method. The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit.

* Asynchronously. A client can register a message listener with a consumer. A message listener is similar to an event listener. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener's onMessage method, which acts on the contents of the message.”

Page 264: Curs Aplicatii distribuite

Curs 12

Partea I – JMS API Programming Model

Page 265: Curs Aplicatii distribuite

Curs 12

Partea I – JMS Non-Durable vs. Durable Topic Subscription

Page 266: Curs Aplicatii distribuite

Curs 12

Partea II – EJB Overview and Products

The Enterprise JavaBeans (EJB) 1.1, 2.0 and 3.0 spe cifications define

an architecture for the development and deployment of

transactional, distributed object applications-base d, server-side

software components.

Java Web Servers with EJB Containers :

� JBoss – RedHat Linux Division – Portlet + BPM/BPEL – Rules Engine

� BEA Web Logic – purchased by Oracle

� GlassFish – Sun Microsystems – purchased by Oracle / IBM lost - Portlet

� Oracle 9iAS – Oracle

� Apache GERONIMO – the only openSource compliant with JEE 5.0

� IBM Web Sphere - Portlet

Page 267: Curs Aplicatii distribuite

Curs 12

Partea II – EJB Container

The Enterprise JavaBeans

specification defines an

architecture for a

transactional, distributed

object system based on

components.

The specification mandates a

programming model; that is,

conventions or protocols

and a set of classes and

interfaces which make up

the EJB API .

Page 268: Curs Aplicatii distribuite

Curs 12

Partea II – EJB Container

Enterprise beans are software components that run in a special

environment called an EJB container .

The EJB container hosts and manages an enterprise bean in the same

manner that the Java Web Server hosts a servlet or a n HTML browser

hosts a Java applet. An enterprise bean cannot func tion outside of an

EJB container.

The EJB container manages every aspect of an enterprise bean at

runtimes including remote access to the bean, secur ity, persistence,

transactions, concurrency, and access to and poolin g of resources.

Page 269: Curs Aplicatii distribuite

Curs 12Partea II – EJB Interaction with EJB ContainerAn enterprise bean depends on the container for eve rything it needs. If an

enterprise bean needs to access a JDBC connection o r another enterprise

bean, it does so through the container; if an enter prise bean needs to access

the identity of its caller, obtain a reference to i tself, or access properties it

does so through the container.

The enterprise bean interacts with its container through 1 of 3

mechanisms (from JNDI are triggered Callback method s or

EJBContext):

� JNDI – Java Naming and Directory Interface – ENC – Environment Naming

Context like: rmiregistry 4 RMI, COS 4 CORBA, UDDI 4 WS

� Callback Methods

� EJBContext

Page 270: Curs Aplicatii distribuite

Curs 12

Partea II – EJB Interaction with EJB Container

JNDI ENC

JNDI – Java Naming and Directory Interface is a standard e xtension to the

Java platform for accessing naming systems like LDA P, NetWare, file

systems, etc. Every bean automatically has access t o a special

naming system called the ENC – Environment Naming Context . The

ENC is managed by the container and accessed by bea ns using JNDI.

The JNDI ENC allows a bean to access resources like JDBC

connections, other enterprise beans, and properties specific to that

bean.

Page 271: Curs Aplicatii distribuite

Curs 12

Partea II – EJB Interaction with EJB Container

Callback Methods

Every bean implements a subtype of the EnterpriseBean interface which

defines several methods, called callback methods. E ach callback

method alerts the bean TO a different event in its lifecycle and the

container will invoke these methods to notify the b ean when it's about

to activate the bean, persist its state to the data base, end a

transaction, remove the bean from memory, etc. The callback methods

give the bean a chance to do some housework immedia tely before or

after some event.

Page 272: Curs Aplicatii distribuite

Curs 12

Partea II – EJB Interaction with EJB Container

EJBContext

Every bean obtains an EJBContext object, which is a reference directly to

the container. The EJBContext interface provides methods for

interacting with the container so that that bean ca n request

information about its environment like the identity of its client, the

status of a transaction, or to obtain remote refere nces to itself.

The EJBContext could be EntityContext or SessionConte xt;

Page 273: Curs Aplicatii distribuite

Curs 12

Partea II – Software Conceptual View of EJB

Page 274: Curs Aplicatii distribuite

Curs 12

Partea II – Software Conceptual View of EJBThe home interface represents the life-cycle methods of the component (create, destroy, find) while the remote interface represents the business method of the bean.

The remote interface extends the javax.ejb.EJBObject.

The home interface extends javax.ejb.EJBHome interface.

These EJB interface types define a standard set of utility methods and provide common base types for all remote and home interfaces.

Page 275: Curs Aplicatii distribuite

Curs 12

Partea II – EJB as Distributed Objects – RMI/IIOP

Page 276: Curs Aplicatii distribuite

Curs 12

Partea II – EJB as Distributed Objects – RMI/IIOP

The remote and home interfaces are types of Java RMI Remote

interfaces . The java.rmi.Remote interface is used by distributed

objects to represent the bean in a different addres s space (process

or machine). An enterprise bean is a distributed ob ject.

That means that the bean class is instantiated and lives in the

container but it can be accessed by applications th at live in other

address spaces – in other JVMs and other computer mac hines.

Page 277: Curs Aplicatii distribuite

Curs 12

Partea II – EJB as Distributed Objects – RMI procedure

To make an object instance in one address space ava ilable in another requires a

little trick involving network sockets. To make the trick work, wrap the instance

in a special object called a skeleton that has a network connection to another

special object called a stub . The stub implements the remote interface so it

looks like a business object. But the stub doesn't contain business logic; it

holds a network socket connection to the skeleton. Every time a business

method is invoked on the stub's remote interface, t he stub sends a network

message to the skeleton telling it which method was invoked. When the

skeleton receives a network message from the stub, it identifies the method

invoked and the arguments, and then invokes the cor responding method on

the actual instance. The instance executes the busi ness method and returns

the result to the skeleton, which sends it to the s tub.

Page 278: Curs Aplicatii distribuite

Curs 12

Partea II – EJB Types in EJB 1.1 and 2.1

EJB Types:

� 1. Entity EJBs

� 1.1 CMP – Content Managed Persistence

� 1.2 BMP – Bean Managed Persistence

� 2. Session EJBs

� 2.1 Stateless

� 2.2 Stateful

� 3. Message Driven Beans – see JMS and JTA

Page 279: Curs Aplicatii distribuite

Curs 12

Partea II – EJB Types in EJB 3.0

EJB Types:

� 1. Session EJBs

� 1.1 Stateless

� 1.2 Stateful

� 2. Message Driven Beans – see JMS and JTA

� Entity EJBs => are included within Java Persistence API

� CMP – Content Managed Persistence

� BMP – Bean Managed Persistence

Page 280: Curs Aplicatii distribuite

Curs 12

Partea II – EJB 2.1 Life-cycle of a Entity Bean

Page 281: Curs Aplicatii distribuite

Curs 12

Partea II – EJB 2.1 Life-cycle of a Stateful Session Bean

Page 282: Curs Aplicatii distribuite

Curs 12

Partea II – EJB 2.1 Life-cycle of a Stateless Session Bean

Page 283: Curs Aplicatii distribuite

Curs 12

Partea II – EJB 2.1 Life-cycle of a Message Driven Bean

Page 284: Curs Aplicatii distribuite

Curs 12Partea II – JMS API API Local Transaction vs. EJB distributed Transaction

Sun: “Distributed transactions can be either of two kinds:

* Container-managed transactions . The EJB container controls the integrity of your transactions without your having to call commit or rollback. Container-managed transactions are recommended for J2EE applications that use the JMS API. You can specify appropriate transaction attributes for your enterprise bean methods. Use the Required transaction attribute to ensure that a method is always part of a transaction. If a transaction is in progress when the method is called, the method will be part of that transaction; if not, a new transaction will be started before the method is called and will be committed when the method returns.

* Bean-managed transactions . You can use these in conjunction with the javax.transaction.UserTransaction interface, which provides its own commit and rollback methods that you can use to delimit transaction boundaries.”

Page 285: Curs Aplicatii distribuite

Curs 12

Partea II – EJB 2.x Life-cycle of a Message Driven Bean

Sun: “Like a stateless session bean, a message-driven bean can have many interchangeable instances running at the same time. The container can pool these instances to allow streams of messages to be processed concurrently. Concurrency can affect the order in which messages are delivered, so you should write your application to handle messages that arrive out of sequence.”

Page 286: Curs Aplicatii distribuite

Curs 12Partea II – EJB 2.x Exemplu combinat Session+MessageDriven

Page 287: Curs Aplicatii distribuite

Curs 12

Partea II – Entity vs. Session EJBThe remote interface defines business methods.

The business methods could be:• accessor and mutator methods(get/set) to read and update information about a business concept – like in Customer interface => entity bean .

• tasks that a bean performs - tasks are more typical of a type of bean called a session bean. Session beans do not represent data like entity beans. They represent business processes or agents that perform a service, like making a reservation at a hotel – like in HotelClerk interface => session bean .

Page 288: Curs Aplicatii distribuite

Curs 12

Partea II – Entity vs. Session EJB

Page 289: Curs Aplicatii distribuite

Curs 12

Partea II – Entity EJB

� 1. Entity EJBsCustomerHome.java – Home interface – EJB life-cycle methods.

Customer.java – Remote Interface – business methods – here get/set.

Page 290: Curs Aplicatii distribuite

Curs 12

Partea II – Entity EJB

� 1. Entity EJBs

CustomerBean.java – EJB entity class

Page 291: Curs Aplicatii distribuite

Curs 12

Partea II – Entity EJB

� 1. Entity EJBs – The entity bean is used to represent data in the da tabase. It

provides an object-oriented interface to data that would normally be

accessed by the JDBC or some other back-end API.

� 1.1 CMP – Container Managed Persistence – the container manages the

persistence of the entity bean. Vendor tools are us ed to map the entity

fields to the database and absolutely no database a ccess code is written

in the bean class.

� 1.2 BMP – Bean Managed Persistence – the entity bean contains

database access code (usually JDBC) and is responsi ble for reading

and writing its own state to the database. BMP enti ties have a lot of help

with this since the container will alert the bean a s to when it's necessary

to make an update or read its state from the databa se.

Page 292: Curs Aplicatii distribuite

Curs 12

Partea II – EJB Types

� 2. Session EJBs – Session beans are used to manage the interactions o f

entity and other session beans, access resources, a nd generally perform

tasks on behalf of the client. Session beans are no t persistent business

objects as are entity beans. They do not represent data in the database.

� 2.1 Stateless – session beans are made up of business methods that

behave like procedures; they operate only on the ar guments passed to

them when they are invoked. Stateless beans are cal led "stateless"

because they are transient; they do not maintain bu siness state between

method invocations.

� 2.2 Stateful – Stateful session beans encapsulate business logic a nd

state specific to a client. Stateful beans are calle d "stateful" because

they do maintain business state between method invo cations, held in

memory and not persistent.

Page 293: Curs Aplicatii distribuite

Curs 12

Partea II – Session EJB

� 2. Session EJBs

HotelClerkHome.java – Home interface – EJB life-cycle methods.

HotelClerk.java – Remote Interface – business methods – here TASKS.

Page 294: Curs Aplicatii distribuite

Curs 12

Partea II – Session Stateless EJB

� 2. Session EJBs - Stateless

HotelClerkBean.java – Stateless Session EJB.

Page 295: Curs Aplicatii distribuite

Curs 12

Partea II – Session Stateless EJB

� 2. Session EJBs - Stateless

HotelClerkBean.java – Stateless Session EJB.

Page 296: Curs Aplicatii distribuite

Curs 12

Partea I – Session Stateful EJB

� 2. Session EJBs - Stateful

HotelClerkBean.java – Stateful Session EJB.

Page 297: Curs Aplicatii distribuite

Curs 12

Partea II – Session Stateful EJB

� 2. Session EJBs - Stateful

HotelClerkBean.java – Stateful Session EJB.

Page 298: Curs Aplicatii distribuite

Curs 12

Partea II – Deploy EJB 1.1 and 2.1In EJB JAR file – within META-INF/ejb-jar.xml.

Page 299: Curs Aplicatii distribuite

Curs 12

Partea II – Deploy EJB 1.1 and 2.1

Page 300: Curs Aplicatii distribuite

Partea II – Deploy EJB 1.1 and 2.1

Page 301: Curs Aplicatii distribuite

Curs 12

Partea II – EJB 1.1, 2.1 vs. EJB 3.0

Page 302: Curs Aplicatii distribuite

Curs 12

Partea II – EJB 1.1, 2.1 vs. EJB 3.0

Page 303: Curs Aplicatii distribuite

Curs 12

Partea II – EJB 1.1, 2.1 vs. EJB 3.0

Page 304: Curs Aplicatii distribuite

Curs 12

Partea II – EJB 1.1 and 2.1 and 3.0

DEMO

Page 305: Curs Aplicatii distribuite

Curs 12

RMI vs CORBA vs Web Services vs EJB

RMI vs CORBA vs Web Services vs EJB

Advantages/Disadvantages

Architecture

Protocols

Naming Services

Q &A + Picture Model

Page 306: Curs Aplicatii distribuite

EXAMEN

Evaluare grila

EXAMEN

Data: 25.05.2010 (Curs 14)

Sala: 2204

Ora: 16.30

Subiecte: Curs si laboratoare

01-13 - inclusiv