Curs Aplicatii distribuite

Post on 12-Apr-2015

139 views 6 download

description

Curs Aplicatii Distribuite Facultate

Transcript of Curs Aplicatii distribuite

Bucuresti2009 – 2010

CURS DAD

Cristian TOMAcristian.toma@ie.ase.ro

Departamentul de Informatica Economica

DEZVOLTAREA APLICATIILOR DISTRIBUITE

DISTRIBUTED APPLICATIONS DEVELOPMENT

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

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

� 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

� 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

� 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

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

� 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

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

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

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

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”

Tehnologii preponderent utilizate

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

DEZVOLTAREA APLICATIILOR 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

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

Curs 0

Agenda

1. Teoria sistemelor 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

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.

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.

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.

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.

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.

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.

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.

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.

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.

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

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

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

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

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

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

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

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

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

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

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

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>

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(...)”

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.

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

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

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() { .... }

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() { .... }

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() { .... }

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.

Curs 3

Partea III – Java Annotations

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

1. @Override2. @Deprecated3. @SupressWarnings

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

AGENDA Curs 4

Partea I – Java Libraries & IO Streams

Partea II – Java Native Interfaces – JNI

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR 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?

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

Curs 4

Partea I – I/O Streams Java – byte level

Curs 4

Partea I – I/O Streams Java – byte level

Curs 4

Partea I – I/O Streams Java – char level

Curs 4

Partea I – I/O Streams Java – char level

Curs 4

Partea I – I/O Streams Java – File

Object File

<<interface>> Serializable

<<interface>> Comparable<File>

<<interface>> Closeable

RandomAccessFile

<<interface>> DataOutput

<<interface>> DataInput Object

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?

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?

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

Curs 5

Partea I – Exceptii – Mod de propagare

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

Curs 5

Partea I – Exceptii – ierarhie de clase

Curs 5

Partea I – Exceptii – C vs Java

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?

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?

Curs 5

Partea III – Multi-threading

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

Curs 5

Partea III – Multi-threading

Curs 5

Partea III – Multi-threading

Curs 5

Partea III – Multi-threading – Concurenta

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

Curs 6

Partea I – Multi-threading - ProducatorConsumator.java

Curs 6

Partea I – Multi-threading – Cooperare

Curs 6

Partea I – Multi-threading – Cooperare

Curs 6

Partea I – Multi-threading – Cooperare

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”?

Curs 6 – SECTIUNEA 2

Partea II – Stiva de protocoale TCP/IP

Curs 6

Partea II – Incapsulare + Multiplexare/Demultiplexare

Curs 6

Partea II – Multiplexare/Demultiplexare

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

Curs 6

Partea II –TCP – RFC 793 – Orientat Conexiune

Cum realizeaza TCP orientarea pe conexiune?

Curs 6

Partea II –TCP – RFC 793

Curs 6

Partea II – UDP – RFC 768 – Neorientat Conexiune

Curs 6

Partea III – C vs Java Socket – UDP

Curs 6

Partea III – Java Socket – UDP

UDPServer

Curs 6

Partea III – Java Socket – UDP

UDPClient

Curs 6

Partea III – C Socket – TCP

Curs 6

Partea III – Java Socket – TCP

import java.net.*;

TCPServer/Client

Curs 6

Partea III – Java Socket – TCP

TCPServer

Curs 6

Partea III – Java Socket – TCP

TCPServer

Curs 6

Partea III – Java Socket – TCP

TCPClient

Curs 6

Partea III – Java Socket – TCP

TCPClient

Curs 6

Partea IV – SNMP – RFC 1157

Curs 6

Partea IV – ASN.1

Curs 6

Partea IV – ASN.1

Curs 6

Partea IV – ASN.1 – TLV

Curs 6

Partea IV – ASN.1 DER – TLV

Curs 6

Partea IV – ASN.1 - OID

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

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)})

Curs 6

Partea IV – ASN.1 - OID

Curs 6

Partea IV – SNMP – RFC 1157

Curs 6

Partea IV – SNMP – RFC 1157

Curs 6

Partea IV – SNMP – RFC 1157

Curs 6

Partea IV – SNMP – RFC 1157

Curs 6

Partea IV – SNMP – RFC 1157

Pentru o intelegere mai buna se consulta ASN.1

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

Curs 7

Partea I – UDP – RFC 768 – Neorientat Conexiune

Curs 7

Partea I –TCP – RFC 793 – Orientat Conexiune

Cum realizeaza TCP orientarea pe conexiune?

Curs 7

Partea I –TCP – RFC 793

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

Curs 7

Partea II – C Socket – TCP

Curs 7

Partea III – SMTP – RFC 2821

Curs 7

Partea III – SMTP – RFC 2821

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.

Curs 7

Partea III – Base64

Curs 7

Partea III – SMTP – RFC 2821

Curs 7

Partea III – SMTP – RFC 2821

Curs 7

Partea III – SMTP – RFC 2821

Curs 7

Partea III – SMTP – RFC 2821

Curs 7

Partea III – SMTP – RFC 2821

Curs 7

Partea III – SMTP – RFC 2821

Curs 7

Partea IV – HTTP – Server HTTP

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

Curs 8

Partea I – HTTP – RFC 2616

Curs 8

Partea I – HTTP – RFC 2616

Curs 8

Partea I – HTTP – URLConnection client

Curs 8

Partea II – FTP – RFC 959

Curs 8

Partea II – FTP – RFC 959

Curs 8

Partea II – FTP – RFC 959 – Server FTP

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

Curs 8

Partea II – FTP – Server FTP

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

Curs 8

Partea II – FTP – Server FTP

Curs 8

Partea II – FTP – Server FTP

Curs 8

Partea II – FTP – Server FTP

Curs 8

Partea II – FTP – Server FTP

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.

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?

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.

AGENDA Curs 9

SECTIUNEA III – Programare web orientata obiect in JEE

Partea I – Tehnologia Java Servlet + Exemple

http://acs.ase.ro

DEZVOLTAREA APLICATIILOR 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

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

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

Curs 9

Partea I – Java Servlet

Curs 9

Partea I – Java Servlet

Curs 9

Partea I – Java Servlet

Curs 9

Partea I – Java Servlet

Curs 9

Partea I – Java Servlet – Request Header

Curs 9

Partea I – Java Servlet – Request Header

Curs 9

Partea I – Java Servlet – Response Codes & Err

Curs 9

Partea I – Java Servlet - Response Codes

Curs 9

Partea I – Java Servlet – Response Headers

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="...">

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())) {…

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);

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

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

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

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>

Curs 10

Partea I – JSP – Java Server Pages

Curs 10

Partea I – JSP – Java Server Pages

Lifecycle JSP

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

Curs 10

Partea I – JSP – Java Server Pages

Curs 10

Partea I – JSP – Java Server Pages

Curs 10

Partea I – JSP – Java Server Pages

Curs 10

Partea I – JSP – Java Server Pages

Curs 10

Partea I – JSP – Java Server Pages

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.

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.

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.

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.

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

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

Curs 10

Partea I – JSP – Java Server Pages – DEMO Taglibs

Curs 10

Partea I – JSP – Java Server Pages – DEMO Taglibs

Curs 10

Partea I – JSP – Java Server Pages – DEMO Taglibs

Curs 10

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

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

Curs 10

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

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.

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

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”.

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

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

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

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

• 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

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() .

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

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

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

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

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

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

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

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

Curs 11

Partea I – CORBA – Basic Architecture

IIOPORB

Client Host Machine

Client Object

ORB

Server Host Machine

Stub

Remote Object

Skeleton

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

Curs 11

Partea I – CORBA – Basic Architecture

Client Server

ORB ORB

response

“Object Bus”

request

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

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

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

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

• 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

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

• 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

• 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

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

• 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

Curs 11

Partea I – CORBA – GIOP and IIOP

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

• 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

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

000001000000000000005e00010000000000186d6179666c792000001000000000000005e00010000000000186d6179666c792000001000000000000005e00010000000000186d6179666c792000001000000000000005e00010000000000186d6179666c792

e73642e6d6f6e6173682e6564752e617500070a000000000036e73642e6d6f6e6173682e6564752e617500070a000000000036e73642e6d6f6e6173682e6564752e617500070a000000000036e73642e6d6f6e6173682e6564752e617500070a000000000036

3a5c6d6179666c792e73642e6d6f6e6173682e6564752e617533a5c6d6179666c792e73642e6d6f6e6173682e6564752e617533a5c6d6179666c792e73642e6d6f6e6173682e6564752e617533a5c6d6179666c792e73642e6d6f6e6173682e6564752e61753

a666f7274756e653a466f7274756e65313a3a49523a466f7274a666f7274756e653a466f7274756e65313a3a49523a466f7274a666f7274756e653a466f7274756e65313a3a49523a466f7274a666f7274756e653a466f7274756e65313a3a49523a466f7274

756e65756e65756e65756e65

Curs 11

Partea I – CORBA – ORB

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

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

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

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

POA Architecture

• A typical example of the relationship between POA and servants

InvocationORB

POA Manager

POA

Curs 11

Partea I – CORBA – ORB

Curs 11

Partea I – CORBA – ORB

Curs 11

Partea I – CORBA – ORB

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

Curs 11

Partea I – CORBA use IDL for independency

Curs 11

Partea I – CORBA use IDL for independency

//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

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

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

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

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

• 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

• 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

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

• 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

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

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

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

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

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

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

DEMO – CORBA Server & Client

Remote Interfaces and StubsIDL Interface

StubRemote Object

(Server)Client Skeleton

implements implements

extends

Curs 11

Partea I – SUN Java IDL

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

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

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

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

Curs 11

Partea II – Web Services – XML-RPC

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

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

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 .

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

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

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.

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

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.

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

Curs 11

Partea II – Web Services – A Java Architecture

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

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

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

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

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

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.

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.

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

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

Curs 12

Partea I – JMS API

Curs 12

Partea I – JMS Point2Popint vs. Topic

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.”

Curs 12

Partea I – JMS API Programming Model

Curs 12

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

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

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 .

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.

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

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.

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.

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;

Curs 12

Partea II – Software Conceptual View of EJB

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.

Curs 12

Partea II – EJB as Distributed Objects – RMI/IIOP

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.

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.

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

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

Curs 12

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

Curs 12

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

Curs 12

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

Curs 12

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

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.”

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.”

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

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 .

Curs 12

Partea II – Entity vs. Session EJB

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.

Curs 12

Partea II – Entity EJB

� 1. Entity EJBs

CustomerBean.java – EJB entity class

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.

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.

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.

Curs 12

Partea II – Session Stateless EJB

� 2. Session EJBs - Stateless

HotelClerkBean.java – Stateless Session EJB.

Curs 12

Partea II – Session Stateless EJB

� 2. Session EJBs - Stateless

HotelClerkBean.java – Stateless Session EJB.

Curs 12

Partea I – Session Stateful EJB

� 2. Session EJBs - Stateful

HotelClerkBean.java – Stateful Session EJB.

Curs 12

Partea II – Session Stateful EJB

� 2. Session EJBs - Stateful

HotelClerkBean.java – Stateful Session EJB.

Curs 12

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

Curs 12

Partea II – Deploy EJB 1.1 and 2.1

Partea II – Deploy EJB 1.1 and 2.1

Curs 12

Partea II – EJB 1.1, 2.1 vs. EJB 3.0

Curs 12

Partea II – EJB 1.1, 2.1 vs. EJB 3.0

Curs 12

Partea II – EJB 1.1, 2.1 vs. EJB 3.0

Curs 12

Partea II – EJB 1.1 and 2.1 and 3.0

DEMO

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

EXAMEN

Evaluare grila

EXAMEN

Data: 25.05.2010 (Curs 14)

Sala: 2204

Ora: 16.30

Subiecte: Curs si laboratoare

01-13 - inclusiv