initial commit

master
Flavien Haas 4 years ago
parent 4c7b30f48e
commit 0106ff985b

Binary file not shown.

Binary file not shown.

@ -0,0 +1,9 @@
public class Main{
public static void main(String[] args){
TacheA a = new TacheA();
Thread t = new Thread(a);
t.start();
TacheB b = new TacheB();
b.start();
}
}

@ -0,0 +1,20 @@
public class TacheA implements Runnable {
public void run(){
while(true){
synchronized(System.out){
System.out.println("Test A 1");
System.out.println("Test A 2");
System.out.println("Test A 3");
System.out.println("Test A 4");
System.out.println("Test A 5");
System.out.println("Test A 6");
try{
Thread.sleep(100);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}

@ -0,0 +1,20 @@
public class TacheB extends Thread {
public void run(){
while(true){
synchronized(System.out){
System.out.println("Test B 1");
System.out.println("Test B 2");
System.out.println("Test B 3");
System.out.println("Test B 4");
System.out.println("Test B 5");
System.out.println("Test B 6");
try{
Thread.sleep(100);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}

@ -0,0 +1 @@
<mxfile host="www.draw.io" modified="2019-11-06T14:00:07.564Z" agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Safari/605.1.15" etag="hX5w2pLr7gsFpP_YXfU-" version="12.2.0" type="device" pages="1"><diagram name="Page-1" id="929967ad-93f9-6ef4-fab6-5d389245f69c">7Vtbc9o4GP01PCaDfAs8Bmh3dyaZYZbMbvsobGFrK1tUFgH66/cTlvENg0nNpVO/ZKxPN0vnHOlIJj1zHG7+EHgZvHKPsJ7R9zY9c9IzjKFpwF8V2CYBxxokAV9QLwmhLDCjP4gO9nV0RT0SFwpKzpmky2LQ5VFEXFmIYSH4ulhswVmx1yX2SSUwczFLo492Fv+XejLQceQMs4w/CfUD3fnAcJKMOXa/+YKvIt1jxCOS5IQ4bUaPMg6wx9e5kPmpZ44F5zJ5CjdjwtS8pnOW1pPb9EV75iiQIYMEgsdd9ueayqhJZRiXIJHMd1fX3j/DhYv+Wk7/e6ZzZ46+f187iweN+ztmK93JW0CwV+k6XtOQYZgZc7TgkZzpHPUemFE/gmcX3oMICLwTISlg86wzJF9C1A0o817wlq/U28YSpj1NjQIu6A9oFqdjg2whNc0AqHyJmaoJ4T5EBYmhzDSdAlQKveJNoeALjqUOuJwxvIzpfD+MEAufRiMuJQ91IT03MByyKbEvm3S0JwKIi/CQSLGFIrqCNdQc0MJClk6vcyR1dCzI8dO0tDq0Mvx90xnE8KBRPgNxq4J4BWxGd0DHUvBvezWpOVpQxsaccUB5stNJhj4jC3kA+5B6Hts1tsQujfw3xYXJA8oiL7uKEzOL/K1nQYUEl1jiBCUFCcNzwqY8ppJy1b5Iyo6WnEZyN1X2qGdPdhEhxzyCQWC6w4oA+muiGNAM2Hq9VNHW6KZryilwBxfC1qlgq2aAh7CSkZXoRN2SqAd2UdSwXd5Y1INO1D8haueuRZ16rBy4nykjrySOlSvqRH2Znfr2okZVc9apurmqUf8w3vci66oR6yTdrqQdsyhp0761+UZVh9ZJ+gxJW/ct6aoNmwrurdzOfbeoavR0bxu1UXVonarPUPXgrlVtmKfRJZ5PUgFrEHM3dSTyntUlJyTnjCupqRCYeKYRgJRWJjIOAD7XCoJyMKAv+0qQ+KoSj3aanGzymZNtmtpQ+SUpaeukqvjQf+zbQx3IqqpEvuaUCApTqRainIbVkI8rGGaIr4RLGqyYsDb55AP3Loc4IQjDkr4XX+4QK3RzU0XzbHkxBiXTkJ4L0iaSQela+fvWUkOWdaKhZNCVhnYk3Y/xJ3jb4Kbv2rxF5/G2RaY5HdEuRjS7AdEyKnkUhzzy3gIaFQiFCoQC9pa4+LGlr83Fqt+QQzX3SR2HjnBoeE0OnbkM7bfP3N6pa9VunLfgXZ2RugLxbKMl4lUaujDxzAbevQHx+seJt/dfpmXdlwGrOVHfM2Uq1zr9K1MGVSjzCuehCm26A/7HDvjlm3j75t/MzQZHwO6Af0Iwd3vANxt8Pc1tAYfOSak3fUSDgrdQC7wxPGUvVOqCa7zR1D/U4ZQDxj6Ai32Z/cFBH9wfzNL+YDtX3h/O87JH+WTn2YROEKlFzqR73GnPWfOV7UacsVvijHNlT2GdZ0N/bc6cPh//CpQZlChjDUv249KUqdrQseiNzd7zsPoJGfZsWSRMYlRKxuSIV6m1qnu3sg6oJDOwI6rPtcDLnRVZRR7xWjSHqDTrRtUcWgfYUz5stPd7SuN3hMF+ujcYqhb9N4DhybkaDJDMfumerGHZvxKYn/4H</diagram></mxfile>

@ -0,0 +1,88 @@
import java.util.ArrayList;
class Producteur implements Runnable {
static final int MAXFILE = 5;
static final int MAXMESSAGES = 50;
private ArrayList<String> messages;
private int nbMessage;
public Producteur() {
messages = new ArrayList<String>();
nbMessage = 0;
}
public void run(){
try {
while (nbMessage < MAXMESSAGES) {
insererMessage();
System.out.println("Message numero "+nbMessage+" produit");
nbMessage++;
Thread.sleep(1000);
}
}
catch (InterruptedException e) {}
}
private synchronized void insererMessage () {
while (messages.size() == MAXFILE) {
System.out.println("File pleine");
try{
this.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
messages.add(new java.util.Date().toString());
}
public synchronized String recupererMessage() {
while (messages.size() == 0) {
System.out.println("File vide");
try{
this.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
String message = (String)messages.get(0);
messages.remove(0);
return message;
}
}
class Consommateur implements Runnable {
static final int MAXMESSAGES = 50;
private int nbMessage;
Producteur producteur;
Consommateur(Producteur p) {
producteur = p ;
nbMessage++;
}
public void run(){
try {
while (nbMessage < MAXMESSAGES) {
String message = producteur.recupererMessage();
System.out.println("Message numero "+nbMessage+" recu : " +message);
nbMessage++;
Thread.sleep(2000);
}
}
catch (InterruptedException e) {}
}
}
public class Distributeur {
public static void main(String[] args){
Producteur prod = new Producteur();
Thread tProd = new Thread(prod);
tProd.start();
Consommateur conso = new Consommateur(prod);
Thread tConso = new Thread(conso);
tConso.start();
}
}

@ -0,0 +1,11 @@
public class Dinner{
public static void main(String[] args) {
Philosophe [] philosophes = new Philosophe[5];
Fourchette [] fourchettes = new Fourchette[5];
for(int i=0; i<fourchettes,lengh;i++){
fourchettes[i] = new Fourchette();
}
for(int i=0)
}
}

@ -0,0 +1,3 @@
public class Fourchette{
}

@ -0,0 +1,6 @@
public class Main {
public static void main(String[] args){
}
}

@ -0,0 +1,13 @@
public class Philosophe{
public Philosophe(){}
public void manger(){
}
public void penser(){
}
}

@ -0,0 +1,113 @@
import java.sql.*;
public class Annuaire {
Connection conn;
public Annuaire(String nomAnnuaire) {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/"+nomAnnuaire+"", "root", "");
// on cree un objet Statement qui va permettre l'execution des requetes
Statement s = conn.createStatement();
// On regarde si la table existe deja
String query = "select * from ANNUAIRE limit 1";
try {
s.executeQuery(query);
} catch(Exception e) {
// sinon on l'a cree
s.execute("create table ANNUAIRE ( " +
" nom VARCHAR( 256 ) NOT NULL PRIMARY KEY, " +
" telephone VARCHAR( 32 ) NOT NULL , " +
" eMail VARCHAR( 256 ) NOT NULL)");
// on ajoute des entrees de test
s.executeUpdate("insert into ANNUAIRE values ('Toto', '0561123456', 'toto@ici.com')");
s.executeUpdate("insert into ANNUAIRE values ('Titi', '0561123457', 'titi@ici.com')");
s.executeUpdate("insert into ANNUAIRE values ('Tata', '0561123458', 'tata@ici.com')");
s.executeUpdate("insert into ANNUAIRE values ('Tutu', '0561123459', 'tutu@ici.com')");
}
} catch(Exception e) {
// il y a eu une erreur
e.printStackTrace();
}
}
public String lireInfos(String nom) {
try {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select * from ANNUAIRE where nom = '"+nom+"'");
if (rs.next()) {
return rs.getString("nom")+":"+rs.getString("telephone")+":"+rs.getString("eMail");
} else {
return null;
}
} catch(Exception ex) {
// il y a eu une erreur
ex.printStackTrace();
return null;
}
}
public boolean ajoutInfos(String infos) {
try {
String [] tab = infos.split(":");
if(tab.length != 3)
return false;
String nom = tab[0];
String telephone = tab[1];
String eMail = tab[2];
Statement s = conn.createStatement();
if (s.executeUpdate("insert into ANNUAIRE values ('"+nom+"', '"+telephone+"', '"+eMail+"')")==1)
return true;
else
return false;
} catch(Exception ex) {
// il y a eu une erreur
ex.printStackTrace();
return false;
}
}
public boolean majInfos(String infos) {
try {
String [] tab = infos.split(":");
if(tab.length != 3)
return false;
String nom = tab[0];
String telephone = tab[1];
String eMail = tab[2];
Statement s = conn.createStatement();
if (s.executeUpdate("update ANNUAIRE set telephone='"+telephone+"', eMail='"+eMail+"' where nom='"+nom+"'")==1)
return true;
else
return false;
} catch(Exception ex) {
// il y a eu une erreur
ex.printStackTrace();
return false;
}
}
public void fermer() throws Exception {
try {
conn.close();
} catch(Exception ex) {
// il y a eu une erreur
ex.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Annuaire annu = new Annuaire("annu");
System.out.println(annu.lireInfos("Toto"));
System.out.println(annu.lireInfos("Bobby"));
annu.ajoutInfos("Bobby:1234:bob@truc.com");
System.out.println(annu.lireInfos("Bobby"));
annu.majInfos("Bobby:12345678:bob@truc.net");
System.out.println(annu.lireInfos("Bobby"));
annu.fermer();
}
}

@ -0,0 +1,142 @@
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class BanqueJDBC {
Connection conn;
public BanqueJDBC(String nomBD) {
try {
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:"+nomBD+";IGNORECASE=TRUE", "sa", "");
// on cree un objet Statement qui va permettre l'execution des requetes
Statement s = conn.createStatement();
// On regarde si la table existe deja
String query = "select id from BANQUE limit 1";
try {
s.executeQuery(query);
} catch(Exception e) {
// sinon on l'a cree
s.execute("create table BANQUE ( " +
" id VARCHAR( 256 ) NOT NULL PRIMARY KEY, " +
" solde REAL , " +
" dateDerniereOperation TIMESTAMP)");
// on ajoute des entrees de test
s.executeUpdate("insert into BANQUE values ('Toto', 1000.5, CURRENT_TIMESTAMP())");
s.executeUpdate("insert into BANQUE values ('Titi', 500.5, CURRENT_TIMESTAMP())");
s.executeUpdate("insert into BANQUE values ('Tata', 20.0, CURRENT_TIMESTAMP())");
s.executeUpdate("insert into BANQUE values ('Tutu', 2000.0, CURRENT_TIMESTAMP())");
}
} catch(Exception e) {
// il y a eu une erreur
e.printStackTrace();
}
}
public boolean creerCompte(String id, double somme) {
try {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select solde from BANQUE where id = '"+id+"'");
if (rs.next()) {
// un compte existe deja avec cet id
return false;
} else {
s.executeUpdate("insert into BANQUE values ('"+id+"', "+somme+", CURRENT_TIMESTAMP())");
return true;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean ajouter(String id, double somme) {
try {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select solde from BANQUE where id = '"+id+"'");
if (rs.next()) {
double solde = rs.getDouble("solde");
solde+=somme;
if (s.executeUpdate("update BANQUE set solde="+solde+",dateDerniereOperation=CURRENT_TIMESTAMP() where id = '"+id+"'")==1)
return true;
else
return false;
} else {
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean retirer(String id, double somme) {
try {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select solde from BANQUE where id = '"+id+"'");
if (rs.next()) {
double solde = rs.getDouble("solde");
solde-=somme;
if (s.executeUpdate("update BANQUE set solde="+solde+",dateDerniereOperation=CURRENT_TIMESTAMP() where id = '"+id+"'")==1)
return true;
else
return false;
} else {
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public Position position(String id) {
try {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select solde,dateDerniereOperation from BANQUE where id = '"+id+"'");
if (rs.next()) {
double solde = rs.getDouble("solde");
Date date = rs.getTimestamp("dateDerniereOperation");
Position p = new Position(solde);
p.setDerniereOperation(date);
return p;
} else {
return null;
}
} catch(Exception ex) {
// il y a eu une erreur
ex.printStackTrace();
return null;
}
}
public void fermer() throws Exception {
try {
conn.close();
} catch(Exception ex) {
// il y a eu une erreur
ex.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
BanqueJDBC banque = new BanqueJDBC("banque");
banque.creerCompte("Bobby", 1000);
System.out.println(" Compte Bobby : "+banque.position("Bobby"));
banque.creerCompte("Bob", 1000);
System.out.println(" Compte Bob : "+banque.position("Bob"));
banque.ajouter("Bobby", 100);
banque.retirer("Bobby", 150);
System.out.println(" Compte Bobby : "+banque.position("Bobby"));
banque.fermer();
}
}

@ -0,0 +1,77 @@
import java.util.Date;
import java.util.HashMap;
public class BanqueSimple {
class CompteEnBanque {
private double solde;
private Date derniereOperation;
public CompteEnBanque(double solde) {
this.solde = solde;
derniereOperation = new Date(); // recupere la date courante
}
public double getSolde() {
return solde;
}
public Date getDerniereOperation() {
return derniereOperation;
}
public void ajouter(double somme) {
solde += somme;
derniereOperation = new Date(); // recupere la date courante
}
public void retirer(double somme) {
solde -= somme;
derniereOperation = new Date(); // recupere la date courante
}
}
HashMap<String, CompteEnBanque> comptes;
public BanqueSimple() {
comptes = new HashMap<String, CompteEnBanque>();
}
public void creerCompte(String id, double somme) {
comptes.put(id, new CompteEnBanque(somme));
}
public boolean compteExiste(String id) {
return comptes.containsKey(id);
}
public void ajouter(String id, double somme) {
CompteEnBanque cpt = comptes.get(id);
cpt.ajouter(somme);
}
public void retirer(String id, double somme) {
CompteEnBanque cpt = comptes.get(id);
cpt.retirer(somme);
}
public double getSolde(String id) {
CompteEnBanque cpt = comptes.get(id);
return cpt.getSolde();
}
public Date getDerniereOperation(String id) {
CompteEnBanque cpt = comptes.get(id);
return cpt.getDerniereOperation();
}
public static void main(String[] args) {
BanqueSimple s = new BanqueSimple();
s.creerCompte("ABC1234", 1000);
s.ajouter("ABC1234", 100);
s.retirer("ABC1234", 30);
double solde = s.getSolde("ABC1234");
Date date = s.getDerniereOperation("ABC1234");
System.out.println("ABC1234 -> " + solde + " " + date);
}
}

Binary file not shown.

@ -0,0 +1,38 @@
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ClientTCP {
public static void main(String args[]) throws Exception {
// Création d'un socket client et connexion avec un serveur fonctionnant sur la même machine et sur le port 40000
Socket sc = new Socket("localhost", 40000);
// Construction d'un BufferedReader pour lire du texte envoyé à travers la connexion socket
BufferedReader entreeSocket = new BufferedReader(new InputStreamReader(sc.getInputStream()));
// Construction d'un PrintStream pour envoyer du texte à travers la connexion socket
PrintStream sortieSocket = new PrintStream(sc.getOutputStream());
String chaine = "";
// Scanner sur System.in
Scanner scanner = new Scanner(System.in);
System.out.println("Tapez vos phrases ou FIN pour arrêter :");
while(!chaine.equalsIgnoreCase("FIN")) {
// lecture clavier
chaine = scanner.nextLine();
sortieSocket.println(chaine); // on envoie la chaine au serveur
// lecture d'une chaine envoyée à travers la connexion socket
String chaine2 = entreeSocket.readLine();
//chaine = entreeSocket.readLine();
System.out.println("Chaine reçue : "+chaine2);
}
// on ferme nous aussi la connexion
sc.close();
}
}

Binary file not shown.

@ -0,0 +1,52 @@
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class ClientUDP {
public static void main(String[] args) throws Exception {
// Création d'un socket UDP sur un port choisi par le système
DatagramSocket socket = new DatagramSocket();
// tampon pour recevoir les données des datagrammes UDP
final byte[] tampon = new byte[1024];
// objet Java permettant de recevoir un datagramme UDP
DatagramPacket reception = new DatagramPacket(tampon, tampon.length);
// Scanner sur System.in
Scanner scanner = new Scanner(System.in);
// On veut envoyer les messages à la même machine
InetAddress destination = InetAddress.getByName("localhost");
String chaine = "";
System.out.println("Tapez vos phrases ou FIN pour arrêter :");
while(!chaine.equalsIgnoreCase("FIN")) {
// lecture clavier
chaine = scanner.nextLine();
// on récupère un tableau des octets de la chaîne
byte [] octetsChaine = chaine.getBytes();
// objet Java permettant d'envoyer un datagramme UDP vers la machine destination et le port 40000
DatagramPacket emission = new DatagramPacket(octetsChaine, octetsChaine.length, destination, 40000);
// on envoie le datagramme UDP
socket.send(emission);
// attente et réception d'un datagramme UDP
socket.receive(reception);
// extraction des données
String chaine2 = new String(reception.getData(), 0, reception.getLength());
System.out.println("Chaine reçue : "+chaine2);
// on replace la taille du tampon au max
// elle a été modifiée lors de la réception
reception.setLength(tampon.length);
}
}
}

@ -0,0 +1,33 @@
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class GestionDUnClientn extends Thread {
private Socket sss;
private GestionProtocole gp;
public void run() {
//Construction d'un BufferedReader pour lire du texte envoyé à traverds la connexion Socket
BufferedReader entreeSocket = new PrintReader(new InputStreamReader);
//Construction d'un PrintStream pour envoyer du texte à travers un Socket
PrintStream sortieSocket = new PrintStream(sss.getOutputStream());
String chaine = " ";
while(chaine != null){
//lecture d'uen chaine envoyée a traverds la connexion socket
chaine = entreeSocket.readLine();
//si elle est nulle c'est que le client a fermee la connexion
if (chaine != null){
System.out.println("requete : " + chaine);
String reponse = gp.traite
}
}
}
}

@ -0,0 +1,72 @@
public class GestionProtocole {
private BanqueSimple bs;
public GestionProtocole() {
bs = new BanqueSimple();
}
public String traite(String requete){
if(requete != null){
String [] tab = requete.split(" ");
switch(tab[0]){
case "CREATION":
if(tab.length == 3){
if(bs.compteExiste(tab[1])) {
return "ERREUR Compte déjà existant";
}
try {
double somme = Double.parseDouble(tab[2]);
bs.creerCompte(tab[1], somme);
return "OK CREATION";
} catch (Exception e){
e.printStackTrace();
}
}
break;
case "POSITION":
if(tab.length == 2){
if(bs.compteExiste(tab[1])) {
return "POS " + bs.getSolde(tab[1]) + " " + bs.getDerniereOperation(tab[1]);
}
else {
return "ERREUR compte inexistant";
}
}
break;
case "AJOUT":
if (tab.length == 3) {
if (bs.compteExiste(tab[1])) {
try {
double somme = Double.parseDouble(tab[2]);
bs.ajouter(tab[1], somme);
return "OK AJOUT";
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
case "RETRAIT":
if (tab.length == 3) {
if (bs.compteExiste(tab[1])) {
try {
double somme = Double.parseDouble(tab[2]);
if (bs.getSolde(tab[1]) >= somme) {
bs.retirer(tab[1], somme);
return "OK RETRAIT";
}
else {
return "KO RETRAIT: pas assez d'argent sur le compte";
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
}
}
return "ERREUR Requête mal formée";
}
}

@ -0,0 +1,44 @@
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServeurTCP {
public static void main(String args[]) throws Exception {
GestionProtocole gp = new GestionProtocole();
// Création d'un socket serveur générique sur le port 40000
ServerSocket ssg = new ServerSocket(40000);
while(true) {
// On attend une connexion puis on l'accepte
Socket sss = ssg.accept();
System.out.println(sss);
// Construction d'un BufferedReader pour lire du texte envoyé à travers la connexion socket
BufferedReader entreeSocket = new BufferedReader(new InputStreamReader(sss.getInputStream()));
// Construction d'un PrintStream pour envoyer du texte à travers la connexion socket
PrintStream sortieSocket = new PrintStream(sss.getOutputStream());
String chaine = "";
while(chaine != null) {
// lecture d'une chaine envoyée à travers la connexion socket
chaine = entreeSocket.readLine();
// si elle est nulle c'est que le client a fermé la connexion
if (chaine != null){
System.out.println("requete : " + chaine);
String reponse = gp.traite(chaine);
sortieSocket.println(reponse); // on envoie la chaine au client
}
}
// on ferme nous aussi la connexion
sss.close();
}
}
}

@ -0,0 +1,43 @@
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ServeurUDP {
public static void main(String[] args) throws Exception {
GestionProtocole gp = new GestionProtocole();
// Création d'un socket UDP sur le port 40000
DatagramSocket socket = new DatagramSocket(40000);
// tampon pour recevoir les données des datagrammes UDP
final byte[] tampon = new byte[1024];
// objet Java permettant de recevoir un datagramme UDP
DatagramPacket dgram = new DatagramPacket(tampon, tampon.length);
while(true) {
// attente et réception d'un datagramme UDP
socket.receive(dgram);
// extraction des données
String chaine = new String(dgram.getData(), 0, dgram.getLength());
if (chaine != null){
System.out.println("requete : " + chaine);
String reponse = gp.traite(chaine);
}
// on renvoie le message au client
socket.send(dgram.setData(reponse));
// on replace la taille du tampon au max
// elle a été modifiée lors de la réception
dgram.setLength(tampon.length);
}
}
}

@ -0,0 +1,113 @@
import java.sql.*;
public class Annuaire {
Connection conn;
public Annuaire(String nomAnnuaire) {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/"+nomAnnuaire+"", "root", "");
// on cree un objet Statement qui va permettre l'execution des requetes
Statement s = conn.createStatement();
// On regarde si la table existe deja
String query = "select * from ANNUAIRE limit 1";
try {
s.executeQuery(query);
} catch(Exception e) {
// sinon on l'a cree
s.execute("create table ANNUAIRE ( " +
" nom VARCHAR( 256 ) NOT NULL PRIMARY KEY, " +
" telephone VARCHAR( 32 ) NOT NULL , " +
" eMail VARCHAR( 256 ) NOT NULL)");
// on ajoute des entrees de test
s.executeUpdate("insert into ANNUAIRE values ('Toto', '0561123456', 'toto@ici.com')");
s.executeUpdate("insert into ANNUAIRE values ('Titi', '0561123457', 'titi@ici.com')");
s.executeUpdate("insert into ANNUAIRE values ('Tata', '0561123458', 'tata@ici.com')");
s.executeUpdate("insert into ANNUAIRE values ('Tutu', '0561123459', 'tutu@ici.com')");
}
} catch(Exception e) {
// il y a eu une erreur
e.printStackTrace();
}
}
public String lireInfos(String nom) {
try {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select * from ANNUAIRE where nom = '"+nom+"'");
if (rs.next()) {
return rs.getString("nom")+":"+rs.getString("telephone")+":"+rs.getString("eMail");
} else {
return null;
}
} catch(Exception ex) {
// il y a eu une erreur
ex.printStackTrace();
return null;
}
}
public boolean ajoutInfos(String infos) {
try {
String [] tab = infos.split(":");
if(tab.length != 3)
return false;
String nom = tab[0];
String telephone = tab[1];
String eMail = tab[2];
Statement s = conn.createStatement();
if (s.executeUpdate("insert into ANNUAIRE values ('"+nom+"', '"+telephone+"', '"+eMail+"')")==1)
return true;
else
return false;
} catch(Exception ex) {
// il y a eu une erreur
ex.printStackTrace();
return false;
}
}
public boolean majInfos(String infos) {
try {
String [] tab = infos.split(":");
if(tab.length != 3)
return false;
String nom = tab[0];
String telephone = tab[1];
String eMail = tab[2];
Statement s = conn.createStatement();
if (s.executeUpdate("update ANNUAIRE set telephone='"+telephone+"', eMail='"+eMail+"' where nom='"+nom+"'")==1)
return true;
else
return false;
} catch(Exception ex) {
// il y a eu une erreur
ex.printStackTrace();
return false;
}
}
public void fermer() throws Exception {
try {
conn.close();
} catch(Exception ex) {
// il y a eu une erreur
ex.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Annuaire annu = new Annuaire("annu");
System.out.println(annu.lireInfos("Toto"));
System.out.println(annu.lireInfos("Bobby"));
annu.ajoutInfos("Bobby:1234:bob@truc.com");
System.out.println(annu.lireInfos("Bobby"));
annu.majInfos("Bobby:12345678:bob@truc.net");
System.out.println(annu.lireInfos("Bobby"));
annu.fermer();
}
}

@ -0,0 +1,14 @@
import java.java.rmi.Remote;
import java.java.rmi.RemoteException;
public interface Banque extends java.rmi.Remote {
void creerCompte(String id, double somme_initiale) throws RemoteException;
void ajouter(String id, double somme) throws RemoteException;
void retirer(String id, double somme) throws RemoteException;
Position position(String id) throws RemoteException;
}

@ -0,0 +1,17 @@
public class BanqueImpl {
}

@ -0,0 +1,142 @@
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class BanqueJDBC {
Connection conn;
public BanqueJDBC(String nomBD) {
try {
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:"+nomBD+";IGNORECASE=TRUE", "sa", "");
// on cree un objet Statement qui va permettre l'execution des requetes
Statement s = conn.createStatement();
// On regarde si la table existe deja
String query = "select id from BANQUE limit 1";
try {
s.executeQuery(query);
} catch(Exception e) {
// sinon on l'a cree
s.execute("create table BANQUE ( " +
" id VARCHAR( 256 ) NOT NULL PRIMARY KEY, " +
" solde REAL , " +
" dateDerniereOperation TIMESTAMP)");
// on ajoute des entrees de test
s.executeUpdate("insert into BANQUE values ('Toto', 1000.5, CURRENT_TIMESTAMP())");
s.executeUpdate("insert into BANQUE values ('Titi', 500.5, CURRENT_TIMESTAMP())");
s.executeUpdate("insert into BANQUE values ('Tata', 20.0, CURRENT_TIMESTAMP())");
s.executeUpdate("insert into BANQUE values ('Tutu', 2000.0, CURRENT_TIMESTAMP())");
}
} catch(Exception e) {
// il y a eu une erreur
e.printStackTrace();
}
}
public boolean creerCompte(String id, double somme) {
try {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select solde from BANQUE where id = '"+id+"'");
if (rs.next()) {
// un compte existe deja avec cet id
return false;
} else {
s.executeUpdate("insert into BANQUE values ('"+id+"', "+somme+", CURRENT_TIMESTAMP())");
return true;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean ajouter(String id, double somme) {
try {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select solde from BANQUE where id = '"+id+"'");
if (rs.next()) {
double solde = rs.getDouble("solde");
solde+=somme;
if (s.executeUpdate("update BANQUE set solde="+solde+",dateDerniereOperation=CURRENT_TIMESTAMP() where id = '"+id+"'")==1)
return true;
else
return false;
} else {
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean retirer(String id, double somme) {
try {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select solde from BANQUE where id = '"+id+"'");
if (rs.next()) {
double solde = rs.getDouble("solde");
solde-=somme;
if (s.executeUpdate("update BANQUE set solde="+solde+",dateDerniereOperation=CURRENT_TIMESTAMP() where id = '"+id+"'")==1)
return true;
else
return false;
} else {
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public Position position(String id) {
try {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select solde,dateDerniereOperation from BANQUE where id = '"+id+"'");
if (rs.next()) {
double solde = rs.getDouble("solde");
Date date = rs.getTimestamp("dateDerniereOperation");
Position p = new Position(solde);
p.setDerniereOperation(date);
return p;
} else {
return null;
}
} catch(Exception ex) {
// il y a eu une erreur
ex.printStackTrace();
return null;
}
}
public void fermer() throws Exception {
try {
conn.close();
} catch(Exception ex) {
// il y a eu une erreur
ex.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
BanqueJDBC banque = new BanqueJDBC("banque");
banque.creerCompte("Bobby", 1000);
System.out.println(" Compte Bobby : "+banque.position("Bobby"));
banque.creerCompte("Bob", 1000);
System.out.println(" Compte Bob : "+banque.position("Bob"));
banque.ajouter("Bobby", 100);
banque.retirer("Bobby", 150);
System.out.println(" Compte Bobby : "+banque.position("Bobby"));
banque.fermer();
}
}

@ -0,0 +1,77 @@
import java.util.Date;
import java.util.HashMap;
public class BanqueSimple {
class CompteEnBanque {
private double solde;
private Date derniereOperation;
public CompteEnBanque(double solde) {
this.solde = solde;
derniereOperation = new Date(); // recupere la date courante
}
public double getSolde() {
return solde;
}
public Date getDerniereOperation() {
return derniereOperation;
}
public void ajouter(double somme) {
solde += somme;
derniereOperation = new Date(); // recupere la date courante
}
public void retirer(double somme) {
solde -= somme;
derniereOperation = new Date(); // recupere la date courante
}
}
HashMap<String, CompteEnBanque> comptes;
public BanqueSimple() {
comptes = new HashMap<String, CompteEnBanque>();
}
public void creerCompte(String id, double somme) {
comptes.put(id, new CompteEnBanque(somme));
}
public boolean compteExiste(String id) {
return comptes.containsKey(id);
}
public void ajouter(String id, double somme) {
CompteEnBanque cpt = comptes.get(id);
cpt.ajouter(somme);
}
public void retirer(String id, double somme) {
CompteEnBanque cpt = comptes.get(id);
cpt.retirer(somme);
}
public double getSolde(String id) {
CompteEnBanque cpt = comptes.get(id);
return cpt.getSolde();
}
public Date getDerniereOperation(String id) {
CompteEnBanque cpt = comptes.get(id);
return cpt.getDerniereOperation();
}
public static void main(String[] args) {
BanqueSimple s = new BanqueSimple();
s.creerCompte("ABC1234", 1000);
s.ajouter("ABC1234", 100);
s.retirer("ABC1234", 30);
double solde = s.getSolde("ABC1234");
Date date = s.getDerniereOperation("ABC1234");
System.out.println("ABC1234 -> " + solde + " " + date);
}
}

@ -0,0 +1,38 @@
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ClientTCP {
public static void main(String args[]) throws Exception {
// Création d'un socket client et connexion avec un serveur fonctionnant sur la même machine et sur le port 40000
Socket sc = new Socket("localhost", 40000);
// Construction d'un BufferedReader pour lire du texte envoyé à travers la connexion socket
BufferedReader entreeSocket = new BufferedReader(new InputStreamReader(sc.getInputStream()));
// Construction d'un PrintStream pour envoyer du texte à travers la connexion socket
PrintStream sortieSocket = new PrintStream(sc.getOutputStream());
String chaine = "";
// Scanner sur System.in
Scanner scanner = new Scanner(System.in);
System.out.println("Tapez vos phrases ou FIN pour arrêter :");
while(!chaine.equalsIgnoreCase("FIN")) {
// lecture clavier
chaine = scanner.nextLine();
sortieSocket.println(chaine); // on envoie la chaine au serveur
// lecture d'une chaine envoyée à travers la connexion socket
String chaine2 = entreeSocket.readLine();
//chaine = entreeSocket.readLine();
System.out.println("Chaine reçue : "+chaine2);
}
// on ferme nous aussi la connexion
sc.close();
}
}

@ -0,0 +1,52 @@
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class ClientUDP {
public static void main(String[] args) throws Exception {
// Création d'un socket UDP sur un port choisi par le système
DatagramSocket socket = new DatagramSocket();
// tampon pour recevoir les données des datagrammes UDP
final byte[] tampon = new byte[1024];
// objet Java permettant de recevoir un datagramme UDP
DatagramPacket reception = new DatagramPacket(tampon, tampon.length);
// Scanner sur System.in
Scanner scanner = new Scanner(System.in);
// On veut envoyer les messages à la même machine
InetAddress destination = InetAddress.getByName("localhost");
String chaine = "";
System.out.println("Tapez vos phrases ou FIN pour arrêter :");
while(!chaine.equalsIgnoreCase("FIN")) {
// lecture clavier
chaine = scanner.nextLine();
// on récupère un tableau des octets de la chaîne
byte [] octetsChaine = chaine.getBytes();
// objet Java permettant d'envoyer un datagramme UDP vers la machine destination et le port 40000
DatagramPacket emission = new DatagramPacket(octetsChaine, octetsChaine.length, destination, 40000);
// on envoie le datagramme UDP
socket.send(emission);
// attente et réception d'un datagramme UDP
socket.receive(reception);
// extraction des données
String chaine2 = new String(reception.getData(), 0, reception.getLength());
System.out.println("Chaine reçue : "+chaine2);
// on replace la taille du tampon au max
// elle a été modifiée lors de la réception
reception.setLength(tampon.length);
}
}
}

@ -0,0 +1,33 @@
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class GestionDUnClientn extends Thread {
private Socket sss;
private GestionProtocole gp;
public void run() {
//Construction d'un BufferedReader pour lire du texte envoyé à traverds la connexion Socket
BufferedReader entreeSocket = new PrintReader(new InputStreamReader);
//Construction d'un PrintStream pour envoyer du texte à travers un Socket
PrintStream sortieSocket = new PrintStream(sss.getOutputStream());
String chaine = " ";
while(chaine != null){
//lecture d'uen chaine envoyée a traverds la connexion socket
chaine = entreeSocket.readLine();
//si elle est nulle c'est que le client a fermee la connexion
if (chaine != null){
System.out.println("requete : " + chaine);
String reponse = gp.traite
}
}
}
}

@ -0,0 +1,72 @@
public class GestionProtocole {
private BanqueSimple bs;
public GestionProtocole() {
bs = new BanqueSimple();
}
public String traite(String requete){
if(requete != null){
String [] tab = requete.split(" ");
switch(tab[0]){
case "CREATION":
if(tab.length == 3){
if(bs.compteExiste(tab[1])) {
return "ERREUR Compte déjà existant";
}
try {
double somme = Double.parseDouble(tab[2]);
bs.creerCompte(tab[1], somme);
return "OK CREATION";
} catch (Exception e){
e.printStackTrace();
}
}
break;
case "POSITION":
if(tab.length == 2){
if(bs.compteExiste(tab[1])) {
return "POS " + bs.getSolde(tab[1]) + " " + bs.getDerniereOperation(tab[1]);
}
else {
return "ERREUR compte inexistant";
}
}
break;
case "AJOUT":
if (tab.length == 3) {
if (bs.compteExiste(tab[1])) {
try {
double somme = Double.parseDouble(tab[2]);
bs.ajouter(tab[1], somme);
return "OK AJOUT";
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
case "RETRAIT":
if (tab.length == 3) {
if (bs.compteExiste(tab[1])) {
try {
double somme = Double.parseDouble(tab[2]);
if (bs.getSolde(tab[1]) >= somme) {
bs.retirer(tab[1], somme);
return "OK RETRAIT";
}
else {
return "KO RETRAIT: pas assez d'argent sur le compte";
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
}
}
return "ERREUR Requête mal formée";
}
}

@ -0,0 +1,26 @@
public class Position {
private double solde;
private Date derniereOperation;
public Position(double solde) {
this.solde = solde;
this.derniereOperation = new Date();
}
public void ajouter(double solde) {
this.solde += solde;
this.derniereOperation = new Date();
}
public void retirer(double solde) {
this.solde -= solde;
this.derniereOperation = new Date();
}
public String afficher() throws RemoteException {
return "Solde : " + solde + " ; date de dernière opération : " + derniereOperation;
}
}

@ -0,0 +1,44 @@
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServeurTCP {
public static void main(String args[]) throws Exception {
GestionProtocole gp = new GestionProtocole();
// Création d'un socket serveur générique sur le port 40000
ServerSocket ssg = new ServerSocket(40000);
while(true) {
// On attend une connexion puis on l'accepte
Socket sss = ssg.accept();
System.out.println(sss);
// Construction d'un BufferedReader pour lire du texte envoyé à travers la connexion socket
BufferedReader entreeSocket = new BufferedReader(new InputStreamReader(sss.getInputStream()));
// Construction d'un PrintStream pour envoyer du texte à travers la connexion socket
PrintStream sortieSocket = new PrintStream(sss.getOutputStream());
String chaine = "";
while(chaine != null) {
// lecture d'une chaine envoyée à travers la connexion socket
chaine = entreeSocket.readLine();
// si elle est nulle c'est que le client a fermé la connexion
if (chaine != null){
System.out.println("requete : " + chaine);
String reponse = gp.traite(chaine);
sortieSocket.println(reponse); // on envoie la chaine au client
}
}
// on ferme nous aussi la connexion
sss.close();
}
}
}

@ -0,0 +1,43 @@
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ServeurUDP {
public static void main(String[] args) throws Exception {
GestionProtocole gp = new GestionProtocole();
// Création d'un socket UDP sur le port 40000
DatagramSocket socket = new DatagramSocket(40000);
// tampon pour recevoir les données des datagrammes UDP
final byte[] tampon = new byte[1024];
// objet Java permettant de recevoir un datagramme UDP
DatagramPacket dgram = new DatagramPacket(tampon, tampon.length);
while(true) {
// attente et réception d'un datagramme UDP
socket.receive(dgram);
// extraction des données
String chaine = new String(dgram.getData(), 0, dgram.getLength());
if (chaine != null){
System.out.println("requete : " + chaine);
String reponse = gp.traite(chaine);
}
// on renvoie le message au client
socket.send(dgram.setData(reponse));
// on replace la taille du tampon au max
// elle a été modifiée lors de la réception
dgram.setLength(tampon.length);
}
}
}

Binary file not shown.

@ -0,0 +1,14 @@
import java.java.rmi.Remote;
import java.java.rmi.RemoteException;
public interface Calc extends java.rmi.Remote {
public int add(int a, int b) throws RemoteException;
public int substract(int a, int b) throws RemoteException;
public int multiply(int a, int b) throws RemoteException;
public int divide(int a, int b) throws RemoteException;
}

@ -0,0 +1,22 @@
import java.java.rmi.RemoteException;
import java.java.rmi.Remote;
import java.java.server.UnicastRemoteObject;
public class CalcImpl implements Calc {
public int add(int a, int b) throws RemoteException{
return a+b;
}
public int substract(int a, int b) throws RemoteException{
return a-b;
}
public int multiply(int a, int b) throws RemoteException{
return a*b;
}
public int divide(int a, int b) throws RemoteException{
return a/b;
}
}

@ -0,0 +1,13 @@
public class ClClient {
public static void main(string[] args) throws Exeption {
Calc x = (Calc) java.rmi.Naming.lookup("SeCalc");
System.out.println(x.add(1, 3));
}
}

@ -0,0 +1,13 @@
import java.java.rmi.RemoteException;
public class SeCalc {
public static void main(String[] args) throws Exception {
java.rmi.registry.LocateRegistry.createRegistry(1099);
CalcImpl x = new CalcImpl();
java.rmi.Naming.rebind("rmi://127.0.0.1/SeCalc", x);
}
}

Binary file not shown.
Loading…
Cancel
Save