---
# System prepended metadata

title: Résumé examEN!!!!!!!!!
tags: [WebService]

---

###### tags: `WebService`
# Résumé examEN!!!!!!!!!

# HTML & javascript

## Ajax
### ex1

#### connection avec ajax a siemens et envoie la valeur sur changement au plc
```
<!DOCTYPE html>
<html lang="fr">
<meta charset="UTF-8">

<head>
    <title>siemens code test</title>
</head>

<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script>
    function send2PLC(variable, value) {
        //prepare Siemens AWP-Var in "" with the value
        var dataString = '"' + variable + '"=' + value;
        $.ajax({
            type: "POST",
            url: "",
            data: dataString
        });
    }
</script>

<body>
    <!-- AWP_In_Variable Name='"qb_Level"' -->
    <input type="text" onchange="send2PLC('qw_Level',value)">
</body>

</html>
```

### ex2

#### Ajax Array montre les valeurs d'un array du plc

```
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        function loadDoc() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {

                    var arr = xhttp.responseText.split(",");

                    document.getElementById("info").innerHTML = arr[0];
                    document.getElementById("i11.0").innerHTML = arr[1];

                }
            };
            xhttp.open("GET", "siemens.html", true);
            xhttp.send();
        }


        var active = setInterval("loadDoc()", 500);
    </script>
</head>

<body>
    <div id="demo">
        <h1>Donné TIA</h1>
        <button type="button" onclick="loadDoc()">Change Content</button>
    </div>

    IW60
    <div id="info">
        ceci est remplacé par Iw22

    </div>
    I11.0
    <div id="i11.0">
        ceci est remplacé par Iw26

    </div>
</body>

</html>
```
#### dans le siemens.html
(:=%IW60: et :=%I11.0: vont étre remplacé par les valeurs du plc)
```
 {"Level": ":=%IW60:", "BtnStart":" :=%I11.0:"}

```
## ex BULP
Utiliser un API. dans ce cas le api (webservice) de bulp.
```
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="referrer" content="no-referrer">
    <title>Document</title>
    <script>
        var xhttp = new XMLHttpRequest();
        function posttoggle() {
            
            xhttp.open("POST", 'http://10.100.129.186/api/v1/device/6001942C43B6', true);
            xhttp.onreadystatechange = callback;
            xhttp.send("action=toggle");
        }
       
        function poston() {
            
            xhttp.open("POST", 'http://10.100.129.186/api/v1/device/6001942C43B6', true);
            xhttp.onreadystatechange = callback;
            xhttp.send("action=on");
        };
        
        function postof() {
            
            xhttp.open("POST", 'http://10.100.129.186/api/v1/device/6001942C43B6', true);
            xhttp.onreadystatechange = callback;
            xhttp.send("action=off");
        };
        function postvert() {
            
            xhttp.open("POST", 'http://10.100.129.186/api/v1/device/6001942C43B6', true);
            xhttp.onreadystatechange = callback;
            xhttp.send("color=0000FF00");
        };
        function postrouge() {
            
            xhttp.open("POST", 'http://10.100.129.186/api/v1/device/6001942C43B6', true);
            xhttp.onreadystatechange = callback;
            xhttp.send("color=00FF0000");
        };
        function postblanc() {
            
            xhttp.open("POST", 'http://10.100.129.186/api/v1/device/6001942C43B6', true);
            xhttp.onreadystatechange = callback;
            xhttp.send("color=FF000000");
        };
        function callback() {
            if (xhttp.readyState == 4) {
                var info= xhttp.responseText;
                document.getElementById("disp").innerHTML = info;
            }
        }

    </script>
</head>

<body>

    <button onclick="posttoggle()">toggle</button>
    <button onclick="poston()">on</button>
    <button onclick="postof()">off</button>
    <button onclick="postvert()">vert</button>
    <button onclick="postrouge()">rouge</button>
    <button onclick="postblanc()">blanc</button>

    <p id="disp" >
      txt </p>

    </div>
</body>

</html>
```

## openweatherMap
```
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        function loadDoc() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {

                    var obj = JSON.parse(xhttp.responseText);
                    document.getElementById("temp").innerHTML = obj.main.temp;
                    document.getElementById("city").innerHTML = obj.main.city;
                }
            };
            xhttp.open("GET", "https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b635ecb76f1ecaad90b1847c38a535e4", true);
            xhttp.send();
        }

        var active = setInterval("loadDoc()", 5000);
    </script>
</head>

<body>
    <div id="demo">
        <h1>The XMLHttpRequest Meteo</h1>
        <button type="button" onclick="loadDoc()">Change Content</button>
    </div>

    temp:
    <div id="temp">

    </div>
    city:
    <div id="city">
    </div>


</body>

</html>
```

# Java

## Myproprieties -> créer un fichier proprieties
```
package communication;
import java.util.*;  
import java.io.*;  
/**
 *
 * @author manuel.gerber
 */

public class MyProperties {  
public static void main(String[] args)throws Exception{  
  
Properties p=new Properties();  
p.setProperty("name","Manu");  
p.setProperty("email","Manu@Test.ch");  
  
p.store(new FileWriter("info.properties"),"Javatpoint Properties Example");  
  
}  
}    
    
```

## Bulp Java -> communiquer avec la lampe bulp(GET/POST)

```
public class RestInJava {

    public static void main(String[] args) throws MalformedURLException, IOException {

        URL obj = new URL("http://10.100.129.186/api/v1/device");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        con.setRequestMethod("GET"); // optional default
        String urlParameters = "";
        
 /*     con.setRequestMethod("POST");
        String urlParameters = ""; // Post-Parameters
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
*/
        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
            System.out.println(inputLine);
        }
        in.close();

    }
}

```


## Jackson Person
crée un fichier json dans le c:/tmp avec les valeurs donné/ crée dans le main créé une map en java et l'affiche dans la console
![](https://i.imgur.com/WHCOQhD.png)

### Person

```
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package Exercice.PersonJackson;

/**
 *
 * @author james.gremaud
 */
public class Person {

    private String name;
    private int age;
    private boolean married;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isMarried() {
        return married;
    }

    public void setMarried(boolean married) {
        this.married = married;
    }
}

```

### MainJackson

```
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package Exercice.PersonJackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 *
 * @author james.gremaud
 */
public class MainJackson {
    public static void main(String[] args) throws JsonProcessingException, IOException {
        ObjectMapper om = new ObjectMapper();
    Person person = new Person();
    Person man = new Person();
    man.setName("Maven");
    man.setMarried(false);
    man.setAge(2);
    person.getAge();
    person.setName("Manuel");
    person.setMarried(true);
    person.setAge(23);
    man.getName();
    //Class 2 JSON 
    String json = om.writeValueAsString(person);
    System.out.println(json);
    
    //Class 2 formated JSON
    json = om.writerWithDefaultPrettyPrinter().writeValueAsString(person);
    System.out.println(json);
    
    //Class 3 JSON-File
    om.writeValue(new File("c:/tmp/person.json"), person);
    
    //JSON 2 Class
    person = om.readValue(json, Person.class);
    System.out.println(person);
    
    //JSON 2 Java
    Map<String, Object> map = om.readValue(json, Map.class);
    System.out.println(map);
    }
    
    
    //JSON 2 map
   /* json = """
         "key":"value"
         "test":"abcdefg"
         """;
    */
}

```

## HttpRequest

va chercher le code html de la page web : www.alainrohr.ch et affiche le code dans la console

```
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package coursData;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

/**
 *
 * @author james.gremaud
 */
public class HttpRequest {

    
 

    public static void main(String[] args) throws IOException {
        String host = "www.alainrohr.ch";
        Socket socket = new Socket(InetAddress.getByName(host), 80);
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        InputStream in = socket.getInputStream();

        out.println("GET / HTTP/1.1\r\nHost:" + host + "\r\n"); //send HTTP request to web server
        int len; //read and writeout the response
        byte[] b = new byte[4096];
        while ((len = in.read(b)) != -1) {
            System.out.write(b, 0, len);
        }
        in.close(); //end program
        out.close();
        socket.close();
    }
}

```

## Server.java ( code du prof mais fonctionne pas sur l'ordi de james):

```
package webcomRequest;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

// Read the full article https://dev.to/mateuszjarzyna/build-your-own-http-server-in-java-in-less-than-one-hour-only-get-method-2k02
public class MyServer {

    public static void main( String[] args ) throws Exception {
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            while (true) {
                try (Socket client = serverSocket.accept()) {
                    handleClient(client);
                }
            }
        }
    }

    private static void handleClient(Socket client) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));

        StringBuilder requestBuilder = new StringBuilder();
        String line;
        while (!(line = br.readLine()).isBlank()) {
            requestBuilder.append(line + "\r\n");
        }

        String request = requestBuilder.toString();
        String[] requestsLines = request.split("\r\n");
        String[] requestLine = requestsLines[0].split(" ");
        String method = requestLine[0];
        String path = requestLine[1];
        String version = requestLine[2];
        String host = requestsLines[1].split(" ")[1];

        List<String> headers = new ArrayList<>();
        for (int h = 2; h < requestsLines.length; h++) {
            String header = requestsLines[h];
            headers.add(header);
        }

        String accessLog = String.format("Client %s, method %s, path %s, version %s, host %s, headers %s",
                client.toString(), method, path, version, host, headers.toString());
        System.out.println(accessLog);


        Path filePath = getFilePath(path);
        if (Files.exists(filePath)) {
            // file exist
            String contentType = guessContentType(filePath);
            sendResponse(client, "200 OK", contentType, Files.readAllBytes(filePath));
        } else {
            // 404
            byte[] notFoundContent = "<h1> not found </h1>".getBytes();
            sendResponse(client, "404 Not Found", "text/html", notFoundContent);
        }

    }

    private static void sendResponse(Socket client, String status, String contentType, byte[] content) throws IOException {
        OutputStream clientOutput = client.getOutputStream();
        clientOutput.write(("HTTP/1.1 \r\n" + status).getBytes());
        clientOutput.write(("ContentType: " + contentType + "\r\n").getBytes());
        clientOutput.write("\r\n".getBytes());
        clientOutput.write(content);
        clientOutput.write("\r\n\r\n".getBytes());
        clientOutput.flush();
        client.close();
    }

    private static Path getFilePath(String path) {
        if ("/".equals(path)) {
            path = "/index.html";
        }

        return Paths.get("/tmp/www", path);
    }

    private static String guessContentType(Path filePath) throws IOException {
        return Files.probeContentType(filePath);
    }

}
```

## TCP Server

```
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package coursData;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

/**
 *
 * @author james.gremaud
 */
public class TCPServer {

    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(2222); // listening on port
        Socket client = server.accept(); // blocked until connection
        InputStream input = client.getInputStream(); // input channel
        byte buf[] = new byte[128]; // prepare receive buffer
        int len = 0;
        while (true) // servers run forever
        {
            len = input.read(buf); // read from stream and count bytes
            byte[] data = Arrays.copyOf(buf, len); // cut relevant bytes
            String output = Arrays.toString(data); // prepare for nice output
            System.out.println(output); // output
        }
    }
}

```
## UDP Socket Server

```
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package coursData;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 *
 * @author james.gremaud
 */
public class UDPSocketServer {
    public static void main(String[] args) throws IOException {
        
        final int SIZE=256;
        byte[] buffer = new byte[SIZE];
        String data;
        
        DatagramSocket socket = new DatagramSocket(5553);
        DatagramPacket p = new DatagramPacket(buffer, SIZE);
        
       do{
        socket.receive(p);
        data = new String(p.getData(),0,p.getLength());
           System.out.println(data);
        //data = Arrays.toString(p.getData());
        
        //System.out.println(Arrays.toString(p.getData()));
       }while (!data.equalsIgnoreCase("end"));
       socket.close();
    }
}

```



# Node-red

## BULP

![](https://i.imgur.com/Hz7zx42.png)

![](https://i.imgur.com/45hEDJc.png)

![](https://i.imgur.com/SvOTLp9.png)

![](https://i.imgur.com/6BVHslN.png)

## what is my ip
![](https://i.imgur.com/D58LFsu.png)

![](https://i.imgur.com/zMXvAxj.png)

![](https://i.imgur.com/o7M0WaZ.png)




## TCP communication
![](https://i.imgur.com/mIBnSL6.png)

![](https://i.imgur.com/dLK3Q4y.png)

![](https://i.imgur.com/44SGsUf.png)

![](https://i.imgur.com/fn4xvR8.png)





## Accélération téléphone communication
![](https://i.imgur.com/ZRUDY47.png)


## JSON
![](https://i.imgur.com/oDeC0Q0.png)
![](https://i.imgur.com/gaa8OFt.png)



## earthquake
![](https://i.imgur.com/C20aXpP.png)

## server REST 
![](https://i.imgur.com/YE5prvl.png)

![](https://i.imgur.com/1M8D6s9.png)

![](https://i.imgur.com/C2CZNNs.png)


function code:
```
var step, result;
 
if(msg.req._parsedUrl.pathname=="/add"){
    step=1;
}

else if(msg.req._parsedUrl.pathname=="/sub"){
    step=2;
}
else if(msg.req._parsedUrl.pathname=="/mul"){
    step=3;
}
else if(msg.req._parsedUrl.pathname=="/div"){
    step=4;
}

switch(step) {
  case 1:
   result=1*msg.payload.x+msg.payload.y*1;
    break;
  case 2:
    result=1*msg.payload.x-msg.payload.y;
    break;
     case 3:
    result=1*msg.payload.x*msg.payload.y;
    break;
     case 4:
    result=1*msg.payload.x/msg.payload.y;
    break;
  default:
}

msg.payload=" Result :"+result+" / x :"+msg.payload.x+" / y :"+msg.payload.y + " / OP :"+ msg.req._parsedUrl.pathname ;
return msg;
```

template code:
```
 <!DOCTYPE html>
    <html lang=”en”>
     <head>
    <title>Response Named Parameters</title>
    </head>
    <body>
    <h1>Server REST</h1>
    Server node-red 
    <br>This is the result of operation:<br>
    <div>{{payload}}</div> 
    </body>
    </html>


```

