Outils pour utilisateurs

Outils du site


projets:2018:stagejava

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
projets:2018:stagejava [2018/10/24 11:52] christian.jacolotprojets:2018:stagejava [2024/04/16 22:26] (Version actuelle) – modification externe 127.0.0.1
Ligne 228: Ligne 228:
  } catch (SQLException ex) {  } catch (SQLException ex) {
  System.out.println(ex.getMessage());  System.out.println(ex.getMessage());
 + }
 + }
 +
 + private static void lireData() {
 + if (conn != null) {
 + try {
 + // créer à partir de la connexion la requête
 + Statement stmt = conn.createStatement();
 + // exécuter la requête
 + ResultSet rs 
 + = stmt.executeQuery("select * from contact");
 + // parcourir le résultat
 + while (rs.next()) {
 + int numeroContact = rs.getInt("numero");
 + String nomContact = rs.getString("nom");
 + String prenomContact = rs.getString("prenom");
 + System.out.println(
 + "Numéro: " + numeroContact 
 + + ", Nom: " + nomContact + ", Prénom: " + prenomContact);
 + }
 + } catch (SQLException e) {
 + System.out.println(e.getMessage());
 + }
 + }
 + }
 +
 + private static void ecrireData() {
 + if (conn != null) {
 + try {
 + // préparer la requête
 + String nomContact = "Blanc";
 + String prenomContact = "Stéphane";
 + String insertionContact = "INSERT INTO contact(nom, prenom) VALUES('" + nomContact + "','"
 + + prenomContact + "')";
 + // créer à partir de la connexion la requête
 + Statement stmt = conn.createStatement();
 + // exécuter la requête
 + stmt.executeUpdate(insertionContact);
 + System.out.println("Insertion de Stéphane: ok");
 + } catch (SQLException e) {
 + System.out.println(e.getMessage());
 + }
 + }
 + }
 +
 + private static void effacerData() {
 + if (conn != null) {
 + try {
 + // préparer la requête
 + int numeroJacolot = 1;
 + String effacterRqt = "DELETE FROM contact WHERE numero = ?";
 + // créer une requête à partir de la connexion
 + PreparedStatement deleteStmt = conn.prepareStatement(effacterRqt);
 + // positionner le paramètre
 + deleteStmt.setInt(1, numeroJacolot);
 + // exécuter la requête
 + deleteStmt.executeUpdate();
 + System.out.println("Christian a été effacé: ok");
 + } catch (SQLException e) {
 + System.out.println(e.getMessage());
 + }
  }  }
  }  }
 } }
 </code> </code>
 +
 +
 +
 +<code>
 +mvn archetype:generate -DarchetypeGroupId=net.mdl29.test -DartifactId=resttest -DarchetypeArtifactId=maven-archetype-quickstart
 +
 +</code>
 +
 +pom.xml
 +
 +<dependencies>
 +    <dependency>
 +        <groupId>org.eclipse.jetty</groupId>
 +        <artifactId>jetty-server</artifactId>
 +        <version>9.2.3.v20140905</version>
 +    </dependency>
 +    <dependency>
 +        <groupId>org.eclipse.jetty</groupId>
 +        <artifactId>jetty-servlet</artifactId>
 +        <version>9.2.3.v20140905</version>
 +    </dependency>
 +    <dependency>
 +        <groupId>org.glassfish.jersey.core</groupId>
 +        <artifactId>jersey-server</artifactId>
 +        <version>2.7</version>
 +    </dependency>
 +    <dependency>
 +        <groupId>org.glassfish.jersey.containers</groupId>
 +        <artifactId>jersey-container-servlet-core</artifactId>
 +        <version>2.7</version>
 +    </dependency>
 +    <dependency>
 +        <groupId>org.glassfish.jersey.containers</groupId>
 +        <artifactId>jersey-container-jetty-http</artifactId>
 +        <version>2.7</version>
 +    </dependency>
 +    <dependency>
 +        <groupId>org.glassfish.jersey.media</groupId>
 +        <artifactId>jersey-media-moxy</artifactId>
 +        <version>2.7</version>
 +    </dependency>
 +    
 +<dependency>
 +    <groupId>org.glassfish.jaxb</groupId>
 +    <artifactId>jaxb-runtime</artifactId>
 +    <version>2.3.2</version>
 +</dependency>
 +    
 +</dependencies>
 +
 +
 +Class EntryPoint.java
 +
 +<code>
 +package net.mdl29.test;
 +
 +import javax.ws.rs.GET;
 +import javax.ws.rs.Path;
 +import javax.ws.rs.Produces;
 +import javax.ws.rs.core.MediaType;
 +
 +@Path("/entry-point")
 +public class EntryPoint {
 +
 +    @GET
 +    @Path("test")
 +    @Produces(MediaType.TEXT_PLAIN)
 +    public String test() {
 +        return "Test";
 +    }
 +}
 +</code>
 +
 +
 +Class App.java
 +
 +<code>
 +package net.mdl29.test;
 +
 +import org.eclipse.jetty.server.Server;
 +import org.eclipse.jetty.servlet.ServletContextHandler;
 +import org.eclipse.jetty.servlet.ServletHolder;
 +
 +public class App {
 +    public static void main(String[] args) throws Exception {
 +        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
 +        context.setContextPath("/");
 +
 +        Server jettyServer = new Server(8080);
 +        jettyServer.setHandler(context);
 +
 +        ServletHolder jerseyServlet = context.addServlet(
 +             org.glassfish.jersey.servlet.ServletContainer.class, "/*");
 +        jerseyServlet.setInitOrder(0);
 +
 +        // Tells the Jersey Servlet which REST service/class to load.
 +        jerseyServlet.setInitParameter(
 +           "jersey.config.server.provider.classnames",
 +           EntryPoint.class.getCanonicalName());
 +
 +        try {
 +            jettyServer.start();
 +            jettyServer.join();
 +        } finally {
 +            jettyServer.destroy();
 +        }
 +    }
 +}
 +</code>
 +
 +
 +
 +
 +Ajouter la gestion du manifeste dans pom.xml
 +
 +<code>
 +<build>
 +...
 +
 +<plugins>
 +    <plugin>
 +      <groupId>org.apache.maven.plugins</groupId>
 +      <artifactId>maven-shade-plugin</artifactId>
 +      <version>1.6</version>
 +      <configuration>
 +        <createDependencyReducedPom>true</createDependencyReducedPom>
 +        <filters>
 +          <filter>
 +            <artifact>*:*</artifact>
 +            <excludes>
 +              <exclude>META-INF/*.SF</exclude>
 +              <exclude>META-INF/*.DSA</exclude>
 +              <exclude>META-INF/*.RSA</exclude>
 +            </excludes>
 +          </filter>
 +        </filters>
 +      </configuration>
 + 
 +      <executions>
 +        <execution>
 +          <phase>package</phase>
 +          <goals>
 +            <goal>shade</goal>
 +          </goals>
 +          <configuration>
 +            <transformers>
 +              <transformer
 +                implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
 +              <transformer
 +                implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
 +                <manifestEntries>
 +                  <Main-Class>net.mdl29.test.App</Main-Class>
 +                </manifestEntries>
 +              </transformer>
 +            </transformers>
 +          </configuration>
 +        </execution>
 +      </executions>
 +    </plugin>
 +  </plugins>
 + ...
 +
 +</build>
 +
 +</code>
 +
 +pom.xml
 +<code>
 +<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>net.mdl29.websocket</groupId>
 +    <artifactId>chatwebsocket</artifactId>
 +    <version>0.0.1-SNAPSHOT</version>
 +    <packaging>war</packaging>
 +    
 +    <properties>
 +        <tomcat.version>9.0.16</tomcat.version>
 +        <websocket.version>1.1</websocket.version>
 +        <jackson.version>2.9.8</jackson.version>
 +    </properties>
 +          
 +    <dependencies>
 +        <!-- Dependency needed by the Web-socket -->
 +        <!-- Tomcat has it, so no need to package into the war file -->
 +        <dependency>
 +            <groupId>javax.websocket</groupId>
 +            <artifactId>javax.websocket-api</artifactId>
 +            <version>${websocket.version}</version>
 +            <scope>provided</scope>
 +        </dependency>
 +        
 +        <!-- Used to serialize the message from the browser -->
 +        <dependency>
 +            <groupId>com.fasterxml.jackson.core</groupId>
 +            <artifactId>jackson-databind</artifactId>
 +            <version>${jackson.version}</version>
 +        </dependency>
 +        
 +        <!-- Sevlet jars for compilation, provided by Tomcat -->
 +        <dependency>
 +            <groupId>org.apache.tomcat</groupId>
 +            <artifactId>tomcat-servlet-api</artifactId>
 +            <version>${tomcat.version}</version>
 +            <scope>provided</scope>
 +        </dependency>
 +    </dependencies>
 +      
 +    <build>
 +        <finalName>${project.artifactId}</finalName>
 +        <plugins>
 +            <plugin>
 +                <artifactId>maven-compiler-plugin</artifactId>
 +                <version>3.1</version>
 +                <configuration>
 +                <source>1.8</source>
 +                <target>1.8</target>
 +                </configuration>
 +            </plugin>
 +                      
 +            <plugin>
 +                <artifactId>maven-war-plugin</artifactId>
 +                <version>2.4</version>
 +                <configuration>
 +                <warSourceDirectory>WebContent</warSourceDirectory>
 +                <failOnMissingWebXml>false</failOnMissingWebXml>
 +                </configuration>
 +            </plugin>
 +        </plugins>
 +    </build>
 +    
 +</project>
 +</code>
 +
 +
 +class ChatWebsocket.java
 +<code>
 +/*
 +  Licensed to the Apache Software Foundation (ASF) under one or more
 +  contributor license agreements.  See the NOTICE file distributed with
 +  this work for additional information regarding copyright ownership.
 +  The ASF licenses this file to You 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.
 + */
 +package net.mdl29.websocket;
 +
 +import java.io.IOException;
 +import java.util.Set;
 +import java.util.concurrent.CopyOnWriteArraySet;
 +import java.util.concurrent.atomic.AtomicInteger;
 +
 +import javax.websocket.OnClose;
 +import javax.websocket.OnError;
 +import javax.websocket.OnMessage;
 +import javax.websocket.OnOpen;
 +import javax.websocket.Session;
 +import javax.websocket.server.ServerEndpoint;
 +
 +@ServerEndpoint(value = "/websocket/chat")
 +public class ChatWebsocket {
 +
 +    private static final String GUEST_PREFIX = "Guest";
 +    private static final AtomicInteger connectionIds = new AtomicInteger(0);
 +    private static final Set<ChatWebsocket> connections =
 +            new CopyOnWriteArraySet<>();
 +
 +    private final String nickname;
 +    private Session session;
 +
 +    public ChatWebsocket() {
 +        nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
 +    }
 +
 +
 +    @OnOpen
 +    public void start(Session session) {
 +        this.session = session;
 +        connections.add(this);
 +        String message = String.format("* %s %s", nickname, "has joined.");
 +        broadcast(message);
 +    }
 +
 +
 +    @OnClose
 +    public void end() {
 +        connections.remove(this);
 +        String message = String.format("* %s %s",
 +                nickname, "has disconnected.");
 +        broadcast(message);
 +    }
 +
 +
 +    @OnMessage
 +    public void incoming(String message) {
 +        // Never trust the client
 +        String filteredMessage = String.format("%s: %s",
 +                nickname, filter(message.toString()));
 +        broadcast(filteredMessage);
 +    }
 +
 +
 +
 +
 +    @OnError
 +    public void onError(Throwable t) throws Throwable {
 +        System.out.println("Chat Error: " + t.toString());
 +    }
 +
 +
 +    private static void broadcast(String msg) {
 +        for (ChatWebsocket client : connections) {
 +            try {
 +                synchronized (client) {
 +                    client.session.getBasicRemote().sendText(msg);
 +                }
 +            } catch (IOException e) {
 +            System.out.println("Chat Error: Failed to send message to client " + e);
 +                connections.remove(client);
 +                try {
 +                    client.session.close();
 +                } catch (IOException e1) {
 +                    // Ignore
 +                }
 +                String message = String.format("* %s %s",
 +                        client.nickname, "has been disconnected.");
 +                broadcast(message);
 +            }
 +        }
 +    }
 +    
 +    public static String filter(String message) {
 +
 +        if (message == null)
 +            return null;
 +
 +        char content[] = new char[message.length()];
 +        message.getChars(0, message.length(), content, 0);
 +        StringBuilder result = new StringBuilder(content.length + 50);
 +        for (int i = 0; i < content.length; i++) {
 +            switch (content[i]) {
 +            case '<':
 +                result.append("&lt;");
 +                break;
 +            case '>':
 +                result.append("&gt;");
 +                break;
 +            case '&':
 +                result.append("&amp;");
 +                break;
 +            case '"':
 +                result.append("&quot;");
 +                break;
 +            default:
 +                result.append(content[i]);
 +            }
 +        }
 +        return result.toString();
 +    }
 +    
 +}
 +</code>
 +
 +Web client chat.xhtml:
 +<code>
 +<?xml version="1.0" encoding="UTF-8"?>
 +<!--
 +  Licensed to the Apache Software Foundation (ASF) under one or more
 +  contributor license agreements.  See the NOTICE file distributed with
 +  this work for additional information regarding copyright ownership.
 +  The ASF licenses this file to You 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.
 +-->
 +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
 +<head>
 +    <title>Apache Tomcat WebSocket Examples: Chat</title>
 +    <style type="text/css"><![CDATA[
 +        input#chat {
 +            width: 410px
 +        }
 +
 +        #console-container {
 +            width: 400px;
 +        }
 +
 +        #console {
 +            border: 1px solid #CCCCCC;
 +            border-right-color: #999999;
 +            border-bottom-color: #999999;
 +            height: 170px;
 +            overflow-y: scroll;
 +            padding: 5px;
 +            width: 100%;
 +        }
 +
 +        #console p {
 +            padding: 0;
 +            margin: 0;
 +        }
 +    ]]></style>
 +    <script type="application/javascript"><![CDATA[
 +        "use strict";
 +
 +        var Chat = {};
 +
 +        Chat.socket = null;
 +
 +        Chat.connect = (function(host) {
 +            if ('WebSocket' in window) {
 +                Chat.socket = new WebSocket(host);
 +            } else if ('MozWebSocket' in window) {
 +                Chat.socket = new MozWebSocket(host);
 +            } else {
 +                Console.log('Error: WebSocket is not supported by this browser.');
 +                return;
 +            }
 +
 +            Chat.socket.onopen = function () {
 +                Console.log('Info: WebSocket connection opened.');
 +                document.getElementById('chat').onkeydown = function(event) {
 +                    if (event.keyCode == 13) {
 +                        Chat.sendMessage();
 +                    }
 +                };
 +            };
 +
 +            Chat.socket.onclose = function () {
 +                document.getElementById('chat').onkeydown = null;
 +                Console.log('Info: WebSocket closed.');
 +            };
 +
 +            Chat.socket.onmessage = function (message) {
 +                Console.log(message.data);
 +            };
 +        });
 +
 +        Chat.initialize = function() {
 +            if (window.location.protocol == 'http:') {
 +                Chat.connect('ws://' + window.location.host + '/examples/websocket/chat');
 +            } else {
 +                Chat.connect('wss://' + window.location.host + '/examples/websocket/chat');
 +            }
 +        };
 +
 +        Chat.sendMessage = (function() {
 +            var message = document.getElementById('chat').value;
 +            if (message != '') {
 +                Chat.socket.send(message);
 +                document.getElementById('chat').value = '';
 +            }
 +        });
 +
 +        var Console = {};
 +
 +        Console.log = (function(message) {
 +            var console = document.getElementById('console');
 +            var p = document.createElement('p');
 +            p.style.wordWrap = 'break-word';
 +            p.innerHTML = message;
 +            console.appendChild(p);
 +            while (console.childNodes.length > 25) {
 +                console.removeChild(console.firstChild);
 +            }
 +            console.scrollTop = console.scrollHeight;
 +        });
 +
 +        Chat.initialize();
 +
 +
 +        document.addEventListener("DOMContentLoaded", function() {
 +            // Remove elements with "noscript" class - <noscript> is not allowed in XHTML
 +            var noscripts = document.getElementsByClassName("noscript");
 +            for (var i = 0; i < noscripts.length; i++) {
 +                noscripts[i].parentNode.removeChild(noscripts[i]);
 +            }
 +        }, false);
 +
 +    ]]></script>
 +</head>
 +<body>
 +<div class="noscript"><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
 +    Javascript and reload this page!</h2></div>
 +<div>
 +    <p>
 +        <input type="text" placeholder="type and press enter to chat" id="chat" />
 +    </p>
 +    <div id="console-container">
 +        <div id="console"/>
 +    </div>
 +</div>
 +</body>
 +</html>
 +</code>
 +
 +Les sources complets avec pom, html, java: {{ :projets:2018:websocket-src.tar.gz |}}
 +
  
projets/2018/stagejava.1540374765.txt.gz · Dernière modification : 2024/04/16 22:26 (modification externe)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki