avr

25

Posted by : admin | On : 25 avril 2024

Sécurité informatique

 

Introduction

La sécurité informatique est devenu de nos jours un élément indispensable dans la sécurisation de l’information tant pour un particulier que pour une entreprise. Afin d’évaluer le degré de sécurité à appliquer il faudra s’attacher dans un premier temps de définir le degré d’importance de l’information visant à être protéger et les moyens technique que nous souhaitons mettre en oeuvre afin de protéger ces informations .

Pour sécuriser les systèmes d’information, la démarche consiste à :

  • évaluer les risques et leur criticité : quels risques et quelles menaces, sur quelle donnée et quelle activité, avec quelles conséquences ?
On parle de « cartographie des risques ». De la qualité de cette cartographie dépend la qualité de la sécurité qui va être mise en oeuvre.
  • rechercher et sélectionner les parades : que va-t-on sécuriser, quand et comment ?
Etape difficile des choix de sécurité : dans un contexte de ressources limitées (en temps, en compétences et en argent), seules certaines solutions pourront être mises en oeuvre.
  • mettre en œuvre les protections, et vérifier leur efficacité.
C’est l’aboutissement de la phase d’analyse et là que commence vraiment la protection du système d’information. Une faiblesse fréquente de cette phase est d’omettre de vérifier que les protections sont bien efficaces (tests de fonctionnement en mode dégradé, tests de reprise de données, tests d’attaque malveillante, etc.)

Nous pouvons décliner à plusieurs niveau la sécurité informatique :

Dans cet article nous allons essayer de voir plus particulièrement la sécurité applicative que nous pouvons appliquer via des algorithme de chiffrement et de hashage. Nous allons essayer d’explorer la librairie Java Security API (JCA Cryptography Architecture) ainsi que la librairie Cipher


Pour commencer un bonne introduction sur le domaine de la sécurité informatique un article que j’ai trouvé intéressant sur techno science : http://www.techno-science.net/?onglet=glossaire&definition=6154 http://igm.univ-mlv.fr/~dr/XPOSE2006/depail/fonctionnement.html

Cryptographie asymétrique

Les concepts de signature numérique sont principalement basés sur la cryptographie asymétrique. Cette technique permet de chiffrer avec un mot de passe et de déchiffrer avec un autre, les deux étant indépendants. Par exemlpe, imaginons que Bob souhaite envoyer des messages secret à Alice. Ils vont pour cela utiliser la cryptographie symétrique. Alice génère tout d’abord un couple de clés. Une clé privée (en rouge) et une clé publique (en vert). Ces clés ont des propriétés particulière vis à vis des algorithmes utilisés. En effet, un message chiffré avec une clé ne peut être déchiffré qu’avec l’autre clé. Il s’agit de fonctions à sens unique.

Alice génère un couple de clés

Alice transmet ensuite la clé publique (en vert) à Bob. Grâce à cette clé, Bob peut chiffrer un texte et l’envoyer à Alice.

Bob chiffre avec la clé publique d'Alice

En utilisant la clé publique d’Alice, Bob est certain de deux choses :

  • Personne ne peut lire le message, puisqu’il est crypté
  •  

  • Seule Alice peut déchiffrer le message, car elle est la seule a possèder la clé privée.
  •  

Nous venons de répondre au besoin de confidentialité des données. Mais la cryptographie asymétrique peut être utilisée d’une autre façon. En effet, on peut également utiliser la clé privée pour chiffrer, la clé publique servant alors à déchiffrer. Le message ainsi chiffré est lisible par toute personne disposant de la clé publique. Ceci n’est pas très utile si l’on cherche la confidentialité. En revanche, une seule personne est susceptible d’avoir chiffré ce message : Alice. Ainsi, si l’on peut déchiffrer un message avec la clé publique d’Alice, c’est forcément la personne à avoir chiffré ce message.

Fonctions de hachage

Je vais maintenant décrire les mécanismes permettant de s’assurer que des données n’ont pas été modifiées : les fonctions de hachage. Une fonction de hachage est un procédé à sens unique permettant d’obtenir une suite d’octets (une empreinte) caractérisant un ensemble de données. Pour tout ensemble de données de départ, l’empreinte obtenue est toujours la même. Dans le cadre de la signature numérique, nous nous intéresseront tout particulièrement aux fonctions de hachage cryptographiques. Celles-ci assurent qu’il est impossible de créer un ensemble de données de départ donnant la même empreinte qu’un autre ensemble. Nous pouvons donc utiliser ces fonctions pour nous assurer de l’intégrité d’un document. Les deux algorithme les plus utilisées sont MD5 et SHA.  A noter que MD5 n’est plus considéré comme sûr par les spécialistes. En effet, une équipe chinoise aurait réussi à trouver une collision complète, c’est à dire deux jeux de données donnant la même empreinte, sans utiliser de méthode de force brute. Aujourd’hui, il serait notamment possible de créer deux pages html au contenu différent, ayant pourtant les mêmes empreintes MD5 (en utilisant notamment les balises <meta>, invisibles dans le navigateur). La falsification de documents pourrait donc être possible.

Signer un document

La signature d’un document utilise à la fois la cryptographie asymétrique et les fonctions de hachage. C’est en effet par l’association de ces deux techniques que nous pouvons obtenir les 5 caractéristiques d’une signature (authentique, infalsifiable, non réutilisable, inaltérable, irrévocable). Imaginons que Alice souhaite envoyer un document signé à Bob.

  • Tout d’abord, elle génére l’empreinte du document au moyen d’une fonction de hachage.
  •  

  • Puis, elle crypte cette empreinte avec sa clé privée.
  •  

Alice signe le document pour l'envoyer à Bob

 

  • Elle obtient ainsi la signature de son document. Elle envoie donc ces deux éléments à Bob
  •  

Alice envoie les deux éléments à Bob
  • Pour vérifier la validité du document, Bob doit tout d’abord déchiffrer la signature en utilisant la clé publique d’Alice. Si cela ne fonctionne pas, c’est que le document n’a pas été envoyé par Alice.
  •  

  • Ensuite, Bob génère l’empreinte du document qu’il a reçu, en utilisant la même fonction de hachage qu’Alice (On supposera qu’ils suivent un protocole établi au préalable).
  •  

  • Puis, il compare l’empreinte générée et celle issue de la signature.
  •  

Bob vérifie la signature d'Alice
  • Si les deux empreintes sont identiques, la signature est validée. Nous sommes donc sûr que :
    • C’est Alice qui a envoyé le document,
    •  

    • Le document n’a pas été modifié depuis qu’Alice l’a signé.
    •  

     

  •  

  • Dans le cas contraire, cela peut signifier que :
    • Le document a été modifié depuis sa signature par Alice,
    •  

    • Ce n’est pas ce document qu’Alice a signé
    •  

     

  •  

 

 

 

/**
 * <p>
 * step 1 create a singleton of the service
 * step 2 Java security API (JCA (Java Cryptography Architecture) to obtain an instance of a message digest object using the algorithm supplied
 * step 3 convert plain data to  byte-representation using UTF-8 encoding format. generate an array of bytes that represent the digested (encrypted) password value
 * step 4 Create a String representation of the byte array representing the digested password value.
 * step 5 newly generated hash stock in String
 *
 * </p>
 * @author artaud antoine
 *
 */

public final class PasswordServiceEncryption
{
	private static PasswordServiceEncryption instance;

	private PasswordServiceEncryption()
	{
	}
       //step 1 create a singleton of the service
	public static synchronized PasswordServiceEncryption getInstance()
	{
		if(instance == null)
		{
			instance = new PasswordServiceEncryption();
		}
		return instance;
	}

	public synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md = null;
		md = MessageDigest.getInstance("SHA-512"); //step 2 Java security API (JCA (Java Cryptography Architecture) to obtain an instance of a message digest object using the algorithm supplied
		System.out.println(plaintext);
		md.reset();
		md.update(plaintext.getBytes("UTF-8")); //step 3 convert plain data to  byte-representation using UTF-8 encoding format. generate an array of bytes that represent the digested (encrypted) password value

		byte raw[] = md.digest(); //step 4 Create a String representation of the byte array representing the digested password value.
		String hash = (new BASE64Encoder()).encode(raw); //step 5 newly generated hash stock in String 

		System.out.println(hash);
		return hash; //step 6
	}

oct

17

Posted by : admin | On : 17 octobre 2019

La lecture

https://thierry-leriche-dessirier.developpez.com/tutoriels/java/vertx/discuter-via-event-bus/

août

20

Posted by : admin | On : 20 août 2019

vimeo

https://vimeo.com/39796236

source code https://github.com/DoctusHartwald/ticket-monster

 

sample pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
 Copyright 2016-2017 Red Hat, Inc, and individual contributors.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>fruits</artifactId>
  <version>15-SNAPSHOT</version>

  <name>Simple Fruits Application</name>
  <description>Spring Boot - CRUD Booster</description>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <maven.min.version>3.3.9</maven.min.version>
    <postgresql.version>9.4.1212</postgresql.version>
    <openjdk18-openshift.version>1.3</openjdk18-openshift.version>

    <spring-boot.version>2.1.3.RELEASE</spring-boot.version>
    <spring-boot-bom.version>2.1.3.Final-redhat-00001</spring-boot-bom.version>
    <maven-surefire-plugin.version>2.20</maven-surefire-plugin.version>
    <fabric8-maven-plugin.version>3.5.40</fabric8-maven-plugin.version>
    <fabric8.openshift.trimImageInContainerSpec>true</fabric8.openshift.trimImageInContainerSpec>
    <fabric8.skip.build.pom>true</fabric8.skip.build.pom>
    <fabric8.generator.from>
      registry.access.redhat.com/redhat-openjdk-18/openjdk18-openshift:${openjdk18-openshift.version}
    </fabric8.generator.from>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>me.snowdrop</groupId>
        <artifactId>spring-boot-bom</artifactId>
        <version>${spring-boot-bom.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

<!-- TODO: ADD Actuator dependency here -->

    <!-- Testing -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

<!-- /actuator/health 
management.endpoints.web.exposure.include=*
/actuator/metrics

/acutuator/metrics/[metric-name]
/actuator/beans
Jaeger and Tracing
-->
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
  <dependency>
          <groupId>org.postgresql</groupId>
          <artifactId>postgresql</artifactId>
          <version>${postgresql.version}</version>
          <scope>runtime</scope>
        </dependency>

</dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>${spring-boot.version}</version> <configuration> <profiles> <profile>local</profile> </profiles> <classifier>exec</classifier> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <profiles> <profile> <id>local</id> <activation> <activeByDefault>true</activeByDefault> </activation> <dependencies> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> </profile> <profile> <id>openshift</id> <dependencies> <!-- TODO: ADD PostgreSQL database dependency here --> </dependencies> <build> <plugins> <plugin> <groupId>io.fabric8</groupId> <artifactId>fabric8-maven-plugin</artifactId> <version>${fabric8-maven-plugin.version}</version> <executions> <execution> <id>fmp</id> <goals> <goal>resource</goal> <goal>build</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project>

test class sample

@RunWith(SpringRunner.class)

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApplicationTest {

    @Autowired
    private FruitRepository fruitRepository;

    @Before
    public void beforeTest() {
    }

    @Test
    public void testGetAll() {
      assertTrue(fruitRepository.findAll().spliterator().getExactSizeIfKnown()==3);
    }

    @Test
    public void getOne() {
      assertTrue(fruitRepository.findById(1).orElse(null)!=null);
    }


Spring REst services
package com.example.service;

import java.util.List;
import java.util.Objects;
import java.util.Spliterator;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@Controller
@RequestMapping(value = "/api/fruits")
public class FruitController {

    private final FruitRepository repository;

    @Autowired
    public FruitController(FruitRepository repository) {
        this.repository = repository;
    }

    @ResponseBody
    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public List getAll() {
        return StreamSupport
                .stream(repository.findAll().spliterator(), false)
                .collect(Collectors.toList());
    }
@ResponseBody
    @ResponseStatus(HttpStatus.CREATED)
    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Fruit post(@RequestBody(required = false) Fruit fruit) {
        verifyCorrectPayload(fruit);

        return repository.save(fruit);
    }

    @ResponseBody
    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public Fruit get(@PathVariable("id") Integer id) {
        verifyFruitExists(id);

        return repository.findById(id).orElse(null);
    }

}

exemple fabric 8

apiVersion: v1
kind: Deployment
metadata:
  name: ${project.artifactId}
spec:
  template:
    spec:
      containers:
        - env:
            - name: DB_USERNAME
              valueFrom:
                 secretKeyRef:
                   name: my-database-secret
                   key: user
            - name: DB_PASSWORD
              valueFrom:
                 secretKeyRef:
                   name: my-database-secret
                   key: password
            - name: JAVA_OPTIONS
              value: "-Dspring.profiles.active=openshift"
Properties openShift
spring.datasource.url=jdbc:postgresql://${MY_DATABASE_SERVICE_HOST}:${MY_DATABASE_SERVICE_PORT}/my_data
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=create

mai

06

Posted by : admin | On : 6 mai 2019

196	242	3	881250949
186	302	3	891717742
22	377	1	878887116
244	51	2	880606923
166	346	1	886397596
298	474	4	884182806
115	265	2	881171488
253	465	5	891628467
305	451	3	886324817
6	86	3	883603013
62	257	2	879372434
286	1014	5	879781125
200	222	5	876042340
210	40	3	891035994
224	29	3	888104457
303	785	3	879485318
122	387	5	879270459
194	274	2	879539794
291	1042	4	874834944
234	1184	2	892079237
119	392	4	886176814
167	486	4	892738452
299	144	4	877881320
291	118	2	874833878
308	1	4	887736532
95	546	2	879196566
38	95	5	892430094
102	768	2	883748450
63	277	4	875747401
160	234	5	876861185
50	246	3	877052329
301	98	4	882075827
225	193	4	879539727
290	88	4	880731963
97	194	3	884238860
157	274	4	886890835
181	1081	1	878962623
278	603	5	891295330
276	796	1	874791932
7	32	4	891350932
10	16	4	877888877
284	304	4	885329322
201	979	2	884114233
276	564	3	874791805
287	327	5	875333916
246	201	5	884921594
242	1137	5	879741196
249	241	5	879641194
99	4	5	886519097
178	332	3	882823437
251	100	4	886271884
81	432	2	876535131
260	322	4	890618898
25	181	5	885853415
59	196	5	888205088
72	679	2	880037164
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.test</groupId>
    <artifactId>initiation-spark-java</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <repositories>
        <repository>
            <id>Apache Spark temp - Release Candidate repo</id>
            <url>https://repository.apache.org/content/repositories/orgapachespark-1080/</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.11</artifactId>
            <version>1.3.1</version>
            <!--<scope>provided</scope>--><!-- cette partie là a été omise dans notre projet pour pouvoir lancer depuis maven notre projet -->
        </dependency>

        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql_2.11</artifactId>
            <version>1.3.1</version>
            <!--<scope>provided</scope>-->
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- we want JDK 1.8 source and binary compatiblility -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
package spark;

import java.io.Serializable;
import java.time.LocalDateTime;

// Spark nécessite des structures sérializables !!
public class Rating implements Serializable {

    public int rating;
    public long movie;
    public long user;
    public LocalDateTime timestamp;

    public Rating(long user, long movie, int rating, LocalDateTime timestamp) {
        this.user = user;
        this.movie = movie;
        this.rating = rating;
        this.timestamp = timestamp;
    }
}
package spark;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;

import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Comparator;
import java.util.Scanner;

/**
 * Calcule la moyenne, le min, le max et le nombre de votes de l'utilisateur n°200.
 */
public class Workshop1 {

    public void run() throws URISyntaxException {
        SparkConf conf = new SparkConf().setAppName("Workshop").setMaster("local[*]");
        JavaSparkContext sc = new JavaSparkContext(conf);
        String ratingsPath = Paths.get(getClass().getResource("/ratings.txt").getPath()).toString();

        JavaRDD<Rating> ratings = sc.textFile(ratingsPath)
                .map(line -> line.split("\\t"))
                .map(row -> new Rating(
                        Long.parseLong(row[0]),
                        Long.parseLong(row[1]),
                        Integer.parseInt(row[2]),
                        LocalDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(row[3]) * 1000), ZoneId.systemDefault())

                ));

        double mean = ratings
                .filter(rating -> rating.user == 200)
                .mapToDouble(rating -> rating.rating)
                .mean();

        double max = ratings
                .filter(rating -> rating.user == 200)
                .mapToDouble(rating -> rating.rating)
                .max(Comparator.<Double>naturalOrder());

        double min = ratings
                .filter(rating -> rating.user == 200)
                .mapToDouble(rating -> rating.rating)
                .min(Comparator.<Double>naturalOrder());

        double count = ratings
                .filter(rating -> rating.user == 200)
                .count();

        System.out.println("mean: " + mean);
        System.out.println("max: " + max);
        System.out.println("min: " + min);
        System.out.println("count: " + count);
        Scanner s=new Scanner(System.in);
        s.hasNextLine();
    }

    public static void main(String... args) throws URISyntaxException {
        new Workshop1().run();
    }
}

 

 

mai

03

Posted by : admin | On : 3 mai 2019

https://javaetmoi.com/2015/04/initiation-apache-spark-en-java-devoxx/

https://github.com/arey/initiation-spark-java/blob/master/src/main/java/org/devoxx/spark/lab/devoxx2015/FirstRDD.java

nov

29

Posted by : admin | On : 29 novembre 2017

https://www.youtube.com/watch?v=miD9QwMKv48

https://github.com/apache/geode

How to create a SpringBoot Gemfire RestfulApi
- Link: http://javasampleapproach.com/spring-…

Spring Data REST provides a mechanics for creating and retrieving an Object from Gemfire storage.
In the article, JavaSampleApproach will introduce you how to create a Gemfire RestfulAPI.

Related Articles:
– How to start Embedded Gemfire Application with SpringBoot
Link: http://javasampleapproach.com/spring-…
– Infinispan Cache Solution | Spring Cache | Spring Boot
Link: http://javasampleapproach.com/spring-…

1. Technologies for SpringBoot Gemfire Restful Api

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE

2. Step to do

– Create a Spring Boot project
– Create a Java Model class
– Config Gemfire storage
– Create a Gemfire repository
– Run & Check result

nov

16

Posted by : admin | On : 16 novembre 2013

 

 

Case study IBM

 

http://www.ibm.com/developerworks/websphere/techjournal/0909_blythe/0909_blythe.html

http://db.apache.org/ojb/docu/guides/objectcache.html#Why+a+cache+and+how+it+works%3F

nov

11

Posted by : admin | On : 11 novembre 2013

 

Thread et processus

Processus concerne une application, un programme

Un programme peut gérer plusieurs petits procesus appelé threads et partagés ses ressources au niveau de la JVM du cluster issu du serveur applicatif

 

Probleme couramment rencontré en informatique

Les sémaphores: utiliser beaucoup dans la gestion des ressources dans son système exploitation .

Le problemes du diner des philosophes: algorithme de Dijkstra

L’algorithme du banquier.

 

Mot clé volatile

uniquement utilisé dans le cas de variable primitive, unique que plusieurs thread peuvent attaquées cette meme variable

Attention ce mot clé ne garanti pas l’atomicité de l’opération

Pas de lock associé dessus

Attention au NPE si la valeur est à null

(Cela indique que la memoire est partagé entre les threads pour cette variable)

Difference entre volatile et synchronized

Synchronized s’applique à un objet et volatile s’applique à la référence de objet

Pour garantir qu’une variable primitive est atomique CF classe AtomiInteger / AtomicReference

 

 

Utilisation synchronized

Exemple Simple : utilisation des mots clé : notify , wait…

Dans cet exemple nous voyons qu’en faites nous appliqueons de manière intuitive le pattern observateur . Dans lexemple suivant nous allons approfondir cette notion

public class AutoBus extends Thread {
	int total = 0;

	public void run() {
		synchronized (this) {
			System.out.println("wait ...");
			for (int i = 0; i < 10; i++){
				total = +i;
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			System.out.println("passenger is given notification call ");
			notify();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		AutoBus bus = new AutoBus();
		bus.start();
		synchronized (bus) {
			System.out.println(" passenger is waiting for the bus");
			bus.wait();
			System.out.println("passenger go notification");
		}
		System.out.println(" total=" + bus.total);
	}
}

Préferer les block synchronized au méthode synchronized .

Ne crée pas de lock au niveau de objet équivalent à synchronized(this) cela veut dire que l’on utilise le monitor of the « this » objet in order to help keeping the object safe . C’est une erreur !!

La bonne pratique est de créer un objet privé qui serviera de monitoring de l’objet et nous garantiera que celui ci nest pas modifié par deux threads concurents :

exemple ligne :

 

        private final Object myMonitor = new Object();

 

 

 

package observerpattern;

/**
 *
 * @author Hugo
 */
public interface ISubject {
        void registerObserver(IObserver o);
        void unregisterObserver(IObserver o);
        void NotifyObservers(String s);
}

public class Subject implements ISubject {

        private final HashSet<IObserver> subscribers;

        public Subject() {
                // Eliminates the possibility of duplicated objects - subscribers.
                this.subscribers = new HashSet<IObserver>();
        }

//        // 1)  Using the "this" object's monitor
//        @Override // Registering subscriber.
//        public synchronized void registerObserver(IObserver o) {
//                System.out.println("Inside register observer method");
//                this.subscribers.add(o);
//        }
//
//        @Override // Unregistering subscriber.
//        public synchronized void unregisterObserver(IObserver o) {
//                this.subscribers.remove(o);
//        }
//
//        @Override
//        public void NotifyObservers(final String s) {
//                // Equivalent to --> public synchronized void NotifyObservers(final String s)
//                synchronized(this){
//                        for (IObserver o : this.subscribers) {
//                                o.Update(s);
//                        }
//                }
//        }

        // 2) Using a private object's monitor!

        private final Object myMonitor = new Object();

        @Override // Registering subscriber.
        public void registerObserver(IObserver o) {

                synchronized ( myMonitor ){
                        System.out.println("Inside register observer method");
                        this.subscribers.add(o);
                }
        }

        @Override // Unregistering subscriber.
        public void unregisterObserver(IObserver o) {

                synchronized ( myMonitor ){
                        this.subscribers.remove(o);
                }
        }

        @Override
        public void NotifyObservers(final String s) {

                synchronized ( myMonitor ){
                        for (IObserver o : this.subscribers) {
                                o.Update(s);
                        }
                }
        }
}

package observerpattern;

/**
 *
 * @author Hugo
 */
public interface IObserver {
        void Update(String s);
        void SubscribeTo(ISubject subject);
        void UnsubscribeTo(ISubject subject);
}

public class Observer  implements IObserver{

        private final String _name;

        public Observer(String name){
                _name = name;
        }

        @Override
        public void Update(String s){
                System.out.println(String.format("%s has received a new message from magazine: %s",_name,s));
        }

        @Override
        public void SubscribeTo(ISubject subject) {
               subject.registerObserver(this);
        }

        @Override
        public void UnsubscribeTo(ISubject subject) {
                subject.unregisterObserver(this);
        }
}

 

Callable et Futur

Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.

Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util.concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.

package callable;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MyCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        Thread.sleep(1000);
        //return the thread name executing this callable task
        return Thread.currentThread().getName();
    }

    public static void main(String args[]){
        //Get ExecutorService from Executors utility class, thread pool size is 10
        ExecutorService executor = Executors.newFixedThreadPool(10);
        //create a list to hold the Future object associated with Callable
        List<Future<String>> list = new ArrayList<Future<String>>();
        //Create MyCallable instance
        Callable<String> callable = new MyCallable();

        for(int i=0; i< 100; i++){
            //submit Callable tasks to be executed by thread pool
            Future<String> future = executor.submit(callable);
            //add Future to the list, we can get return value using Future
            list.add(future);
        }
        for(Future<String> fut : list){
            try {
                //print the return value of Future, notice the output delay in console
                // because Future.get() waits for task to get completed
                System.out.println(new Date()+ "::"+fut.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        //shut down the executor service now
        executor.shutdown();
    }

}

Multithreading  in a loop

 

public class ExecutorServiceExample {  

  private static class MyTask implements Callable<Double> {  

    private final int index;  

    private MyTask(Integer idx) { index = idx; }  

    public Double call() throws InterruptedException {
      System.out.println("Working on index " + index + "...");  

      // pretend we're doing something long and complex here...
      Thread.sleep(2000);  

      System.out.println("Completed index " + index);  

      // pretend this is the net result of the long, complex thing we did:
      return index * .001;
    }
  }  

  public static void main(String[] args) throws InterruptedException, ExecutionException {  

    ExecutorService execs = Executors.newFixedThreadPool(10);  

    List<Future<Double>> results = new ArrayList<Future<Double>>();  

    for (int i = 0; i < 100; i++) {
      Future<Double> result = execs.submit(new MyTask(i));
      results.add(result);
    }  

    // this is just a signal; it won't terminate until all tasks are completed
    execs.shutdown();
    System.out.println("Sent shutdown signal");  

    execs.awaitTermination(60, TimeUnit.MINUTES);  

    System.out.println("Results: ");
    int index = 0;
    for (Future<Double> result : results) {
      System.out.println(index++ + ":\t" + result.get());
    }
  }
}

Autre resources

http://www.journaldev.com/1034/java-blockingqueue-example-implementing-producer-consumer-problem

http://doanduyhai.wordpress.com/2012/08/04/design-pattern-the-asynchronous-dispatcher/

http://www.journaldev.com/1162/

août

17

Posted by : admin | On : 17 août 2013

 

A good walk around

http://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse#144349

mai

11

Posted by : admin | On : 11 mai 2012

This tutorial is inspired from (run under glassfish)

http://java.dzone.com/articles/ejb-30-and-spring-25

In this following page I modified the spring configuration and test the deployment on Jboss 4.2

Environnement Tool

- Java 5 or higher
- Spring Tools suite (or Eclipse  )
- Jboss 4.2.x (tested on version jboss-4.2.3.GA)
- Spring 2.5.6

 

The data layer is using @Entity to define the Table (or pojo) that will correspond to our data model
Here we have a simple table called Customer with a series of fields

  • then we need to ask ourself which services do we want to expose to others ?

As in Facade design pattern we will expose an interface and the method that the client can attack on the server side
So here we define an interface call CustomerService that is annoted with @Remote
Then we’ve implement the CRUD operation and @PersistenceContext in  CustomerServiceImpl class

Then in the second part of the tutorial we are viewing how to bind Spring with EJB 3
To do that you’ll need to investigate the name of jndi register in your server.
The tag jee:jndi-lookup will bind both EJB context  and spring context
Once your project is set up you can easily use Spring test or more simply define a Java project that reference your Ejb project (write a main )

 

When Should I use EJB or Spring ?

Personnaly I go through EJB 2 or 3 for exposing the services that I want others to use . In this sample projet we have seen how simple it is to expose some operation on Customer .

I prefer to use EJB also for Datalayer  (DAO Data access Object) , We only need a persistence configuration file and an EntityManager, whereas in Spring the configuration is quite verbose .

Meanwhile I will also use spring because it’s modular and scapable for integration process , feed of data …
It’s also well oriented on Framework integration , so the integration overhall remain less painful .
Recently Springsource team has also develop in spring source view module for spring batch and spring integration. As a consequence we can realize and spot out easily what is going on around all that mess.

What also we need to keep in mind is that main vendors IBM websphere, Weblogic, jboss and others are ease to respect J2EE specification standard; so you’re project in EJB will remain supported for a while
Finaly for large scale system where high volum, deman is need you will better use EJB standard to support the charge and the concurrency process.

Below you will find out the project code as well as the check you need to realize to ensure that the deployment part on application server has been realized successfully .

The server deployment can be a little touchy , you need to bump your head around for a certain time at the beginning but after searching on forum and reading vendor documentation it’s should be allright !!

In this other article , I expose how you can test out easily your project to see if you can make it work it out .
Basicaly there 3 method , you can right a main if your project is small , an other way is to write Junit for unit test . Finally you can use Spring Test and get the power of Ioc mechanism .

Go further

http://what-when-how.com/enterprise-javabeans-3/combining-the-power-of-ejb-3-and-spring/

 

Project look like

 

 

 

Setup Jboss

 

 

When you start your server you should have the following log

17:30:56,041 INFO  [SessionFactoryObjectFactory] Factory name: persistence.units:jar=CustomerService.jar,unitName=Customer
17:30:56,041 INFO  [NamingHelper] JNDI InitialContext properties:{java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory, java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces}
17:30:56,041 INFO  [SessionFactoryObjectFactory] Bound factory to JNDI name: persistence.units:jar=CustomerService.jar,unitName=Customer
17:30:56,041 WARN  [SessionFactoryObjectFactory] InitialContext did not implement EventContext
17:30:56,041 INFO  [SchemaUpdate] Running hbm2ddl schema update
17:30:56,041 INFO  [SchemaUpdate] fetching database metadata
17:30:56,041 INFO  [SchemaUpdate] updating schema
17:30:56,072 INFO  [TableMetadata] table found: PUBLIC.CUSTOMER
17:30:56,072 INFO  [TableMetadata] columns: [first_name, middle_name, last_name, email_id, customer_id]
17:30:56,072 INFO  [TableMetadata] foreign keys: []
17:30:56,072 INFO  [TableMetadata] indexes: [sys_idx_60]
17:30:56,072 INFO  [SchemaUpdate] schema update complete
17:30:56,072 INFO  [NamingHelper] JNDI InitialContext properties:{java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory, java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces}
17:30:56,150 INFO  [JmxKernelAbstraction] creating wrapper delegate for: org.jboss.ejb3.stateless.StatelessContainer
17:30:56,150 INFO  [JmxKernelAbstraction] installing MBean: jboss.j2ee:jar=CustomerService.jar,name=CustomerServiceImpl,service=EJB3 with dependencies:
17:30:56,150 INFO  [JmxKernelAbstraction]     persistence.units:jar=CustomerService.jar,unitName=Customer
17:30:56,182 INFO  [EJBContainer] STARTED EJB: com.ejb.service.CustomerServiceImpl ejbName: CustomerServiceImpl
17:30:56,213 INFO  [EJB3Deployer] Deployed: file:/C:/jboss-4.2.3.GA-jdk6/jboss-4.2.3.GA/server/default/deploy/CustomerService.jar
17:30:56,229 INFO  [DefaultEndpointRegistry] register: jboss.ws:context=CustomerService,endpoint=CustomerServiceImpl
17:30:56,338 INFO  [TomcatDeployer] deploy, ctxPath=/CustomerService, warUrl=…/tmp/deploy/CustomerService.jar38776.war/
17:30:57,432 INFO  [WSDLFilePublisher] WSDL published to: file:/C:/jboss-4.2.3.GA-jdk6/jboss-4.2.3.GA/server/default/data/wsdl/CustomerService.jar/CustomerService38777.wsdl
17:30:57,744 INFO  [TomcatDeployer] deploy, ctxPath=/jmx-console, warUrl=…/deploy/jmx-console.war/
17:30:57,885 INFO  [Http11Protocol] Démarrage de Coyote HTTP/1.1 sur http-127.0.0.1-8080

 

Compy spring.jar in the path

<Jboss_HOME>\server\default\lib

 

check the deployement of webservices

http://127.0.0.1:8080/CustomerService/CustomerServiceImpl?wsdl

Jmx console

 

 

 

check the deployement of EJB3

 

Check the JNDI view deployment you should view

 

 

 

Mbean database=localDB,service=Hypersonic call the Mbean Hypersonic and click start

 

 

package com.ejb.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
//@Table(name = "CUSTOMER", catalog = "", schema = "ADMIN")
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "CUSTOMER_ID")
    private Long customerId;
    @Column(name = "FIRST_NAME")
    private String firstName;
    @Column(name = "LAST_NAME")
    private String lastName;
    @Column(name = "MIDDLE_NAME")
    private String middleName;
    @Column(name = "EMAIL_ID")
    private String emailId;

    public Customer() {
    }

    public Customer(Long customerId) {
        this.customerId = customerId;
    }

    public Long getCustomerId() {
        return customerId;
    }

    public void setCustomerId(Long customerId) {
        this.customerId = customerId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

}

package com.ejb.service;

import java.util.Collection;

import javax.ejb.Remote;

import com.ejb.domain.Customer;

@Remote
public interface CustomerService {

    Customer create(Customer info);

    Customer update(Customer info);

    void remove(Long customerId);

    Collection<Customer> findAll();

    Customer[] findAllAsArray();

    Customer findByPrimaryKey(Long customerId);
}

package com.ejb.service;

import java.util.Collection;

import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.ejb.domain.Customer;

@WebService(name = "CustomerService", serviceName = "CustomerService", targetNamespace = "urn:CustomerService")
@SOAPBinding(style = SOAPBinding.Style.RPC)
@Stateless(name = "CustomerServiceImpl")
public class CustomerServiceImpl implements CustomerService {

    @PersistenceContext(name="Customer")
    private EntityManager manager;

    @WebMethod
    public Customer create(Customer info) {
        this.manager.persist(info);
        return info;
    }

    @WebMethod
    public Customer update(Customer info) {
        return this.manager.merge(info);
    }

    @WebMethod
    public void remove(Long customerId) {
        this.manager.remove(this.manager.getReference(Customer.class, customerId));
    }

    public Collection<Customer> findAll() {
        Query query = this.manager.createQuery("SELECT c FROM Customer c");
        return query.getResultList();
    }

    @WebMethod
    public Customer[] findAllAsArray() {
        Collection<Customer> collection = findAll();
        return (Customer[]) collection.toArray(new Customer[collection.size()]);
    }

    @WebMethod
    public Customer findByPrimaryKey(Long customerId) {
        return (Customer) this.manager.find(Customer.class, customerId);
    }

}

package com.spring.service;

import com.ejb.domain.Customer;

public interface CustomerManager {
    public void addCustomer(Customer customer);
    public void removeCustomer(Long customerId);
    public Customer[] listCustomers();
}

package com.spring.service;

import com.ejb.domain.Customer;
import com.ejb.service.CustomerService;

public class CustomerManagerImpl implements CustomerManager {

    CustomerService customerService;

    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }

    public void removeCustomer(Long customerId) {
        customerService.remove(customerId);
    }

    public Customer[] listCustomers() {
        return customerService.findAllAsArray();
    }

    public void addCustomer(Customer customer) {
        customerService.create(customer);
    }
}

Persistence Unit

here we use for the example HSQL , it’s embedded on Jboss Server

the configuration file will be as follow :

<persistence>
   <persistence-unit name="Customer">
   	 <class>com.ejb.domain.Customer</class>
      <jta-data-source>java:/DefaultDS</jta-data-source>
      <properties>
      	 <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
         <property name="hibernate.hbm2ddl.auto" value="update"/>
      </properties>
   </persistence-unit>
</persistence>
  • in MySQL the configuration will be
<properties>

			<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" />
			<property name="javax.persistence.jdbc.user" value="root" />
			<property name="javax.persistence.jdbc.password" value="" />
			<!-- EclipseLink should create the database schema automatically -->
			<property name="eclipselink.ddl-generation" value="create-tables" />
			<property name="eclipselink.ddl-generation.output-mode"
				value="database" />
		</properties>

 

 

the Spring configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">

	<!-- Use a custom JNDI bean factory configured not to prepend lookups with
		"java:comp/env" -->
	<bean id="jndiFactory">
		<property name="resourceRef" value="false" />
	</bean>

	<!-- Configure the CommonAnnotationBeanPostProcessor to always use JNDI
		lookup (for EJBs) and use the custom JNDI bean factory above. -->
	<bean
		class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
		<property name="alwaysUseJndiLookup" value="true" />
		<property name="jndiFactory" ref="jndiFactory" />
	</bean>

	<!-- <jee:jndi-lookup id="customerService"
		jndi-name="com.ejb.service.CustomerServiceImpl">
	</jee:jndi-lookup> -->

	<jee:jndi-lookup id="customerService" jndi-name="CustomerServiceImpl/remote"
		lookup-on-startup="false" proxy-interface="com.ejb.service.CustomerService"></jee:jndi-lookup>

	<bean id="manageCustomer">
		<property name="customerService" ref="customerService" />
	</bean>
</beans>

 

The client test configuration project

 

you’re project should like like this

 

*in the classpath create a jndi.propertiesand java  class client

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost:1099
package com.spring.client;

import javax.naming.Context;
import javax.naming.InitialContext;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ejb.domain.Customer;
import com.ejb.service.CustomerService;
import com.spring.service.CustomerManager;

public class SpringAndEJBMain {

    public static void main(String[] args) {

        try {
            Context context = new InitialContext();
            CustomerService stock = (CustomerService) context.lookup("CustomerService/remote");

             ApplicationContext contextSpring =new ClassPathXmlApplicationContext("SpringXMLConfig.xml");

             CustomerManager service = (CustomerManager) contextSpring.getBean("manageCustomer");
             Customer customer = new Customer();
             customer.setFirstName("Meera");
             customer.setLastName("Subbarao");
             customer.setMiddleName("B");
             customer.setEmailId("meera@springandejb.com");
             customer.setCustomerId(new Long(1));

             service.addCustomer(customer);
             for (Customer cust : service.listCustomers()) {
                 System.out.println(cust.getFirstName());
                 System.out.println(cust.getLastName());
                 System.out.println(cust.getMiddleName());
                 System.out.println(cust.getEmailId());

             }
            // service.removeCustomer(new Long(1));

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

    }
}