Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.projet.adminclient;
- import com.fasterxml.jackson.core.type.TypeReference;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.google.gson.Gson;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.ProtocolException;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.time.LocalDate;
- import java.time.format.DateTimeFormatter;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.GregorianCalendar;
- import java.util.ResourceBundle;
- import java.util.Set;
- import java.util.TreeSet;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import javafx.animation.FadeTransition;
- import javafx.application.Platform;
- import javafx.collections.ObservableList;
- import javafx.event.ActionEvent;
- import javafx.fxml.FXML;
- import javafx.fxml.Initializable;
- import javafx.scene.control.Button;
- import javafx.scene.control.DatePicker;
- import javafx.scene.control.ListView;
- import javafx.scene.control.TextField;
- import javafx.scene.paint.Paint;
- import javafx.scene.text.Text;
- import javafx.util.Duration;
- import org.apache.pdfbox.pdmodel.PDDocument;
- import org.apache.pdfbox.pdmodel.PDDocumentInformation;
- import org.apache.pdfbox.pdmodel.PDPage;
- import org.apache.pdfbox.pdmodel.PDPageContentStream;
- import org.apache.pdfbox.pdmodel.font.PDType1Font;
- import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
- public class FXMLController implements Initializable {
- @FXML
- private Button btnCreate;
- @FXML
- private Button btnDelete;
- @FXML
- private Button btnList;
- @FXML
- private Button btnGeneratePDF;
- @FXML
- private ListView<String> lvUsers;
- @FXML
- private Button btnQuit;
- @FXML
- private TextField createPassword;
- @FXML
- private TextField createLogin;
- @FXML
- private Text infoCreate;
- @FXML
- private Text infoPDF;
- @FXML
- private DatePicker dateStart;
- @FXML
- private DatePicker dateEnd;
- private final int ServiceAdminPort = 8085;
- private final int ServiceLogEditorPort = 8084;
- //listView
- ObservableList<String> ol = javafx.collections.FXCollections.observableArrayList();
- /**
- * **************************************
- * Appeler le Web service POST du BackEnd Afficher le code de retour du
- * service
- *
- * @param event **************************************
- */
- @FXML
- private void hBtnCreate(ActionEvent event) {
- try {
- //construire l'URL d'appel du service WS-R
- final URL apiEndpoint = new URL(String.format("http://%s:%d/user/create", "localhost", ServiceAdminPort));
- // Preparer laconnection http
- final HttpURLConnection connection = (HttpURLConnection) apiEndpoint.openConnection();
- try {
- // Spécifier que c'est une methode POST
- connection.setRequestMethod("POST");
- } catch (ProtocolException ex) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
- }
- //spécifier que la connexion sera en entrée et sortie
- connection.setDoInput(true);
- connection.setDoOutput(true);
- String data = "login=" + URLEncoder.encode(createLogin.getText(), "UTF-8")
- + "&password=" + URLEncoder.encode(createPassword.getText(), "UTF-8");
- OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
- wr.write(data);
- wr.flush();
- //récupérer le code de la réponse
- final int code = connection.getResponseCode();
- //afficher le code de la réponse
- // ol.add("RETOUR GET=" + code);
- //en fonction du code réponse
- switch (code) {
- case 200:
- case 201:
- //lire le corps de la réponse http => Json
- BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- StringBuilder sb = new StringBuilder();
- String line;
- while ((line = br.readLine()) != null) {
- sb.append(line).append("\n");
- }
- br.close();
- String json = sb.toString();
- Reponse msg = new Gson().fromJson(sb.toString(), Reponse.class);
- infoCreate.setText(msg.getReponse());
- infoCreate.setFill(Paint.valueOf("GREEN"));
- hBtnList(event);
- break;
- default:
- infoCreate.setText("Erreur insertion");
- infoCreate.setFill(Paint.valueOf("RED"));
- break;
- }
- } catch (MalformedURLException ex) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
- } catch (IOException ex) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
- infoCreate.setText("Erreur WebService");
- infoCreate.setFill(Paint.valueOf("RED"));
- }
- FadeTransition ft = new FadeTransition(Duration.millis(4000), infoCreate);
- ft.setFromValue(1.0);
- ft.setToValue(0);
- ft.play();
- }
- /**
- * ***************************
- * Initializer les objets du controller
- *
- * @param url
- * @param rb ***************************
- */
- @Override
- public void initialize(URL url, ResourceBundle rb) {
- //affecter l'ObservableList à la listView
- lvUsers.setItems(ol);
- String date = new SimpleDateFormat("dd-MM-yyyy").format(Calendar.getInstance().getTime());
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
- LocalDate localDate = LocalDate.parse(date, formatter);
- dateStart.setValue(localDate);
- dateEnd.setValue(localDate);
- hBtnList(null);
- }
- /**
- * **************************************
- * Appler le service DELETE et afficher le code retour du service
- *
- * @param event **************************************
- */
- @FXML
- private void hBtnDelete(ActionEvent event) {
- String string = lvUsers.getSelectionModel().getSelectedItem();
- System.out.println(string);
- Pattern pattern = Pattern.compile("^.*id=(\\d*).*");
- Matcher matcher = pattern.matcher(string);
- String id = null;
- while (matcher.find()) {
- id = matcher.group(1);
- }
- if (id != null) {
- ol.clear();
- try {
- final URL apiEndpoint = new URL(String.format("http://%s:%d/user/delete/" + id, "localhost", ServiceAdminPort));
- //construire l'URL d'appel du service WS-R
- final HttpURLConnection connection = (HttpURLConnection) apiEndpoint.openConnection();
- try {
- // C'est une methode DELETE
- connection.setRequestMethod("DELETE");
- } catch (ProtocolException ex) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
- }
- //spécifier que la connexion sera en entrée et sortie
- connection.setDoInput(true);
- connection.setDoOutput(true);
- //recuperation code retour
- final int code = connection.getResponseCode();
- //afficher code retour dasn la listView
- // ol.add("RETOUR DELETE=" + code);
- } catch (MalformedURLException ex) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
- } catch (IOException ex) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
- ol.add("Le Web service DELETE ne répond pas !");
- }
- hBtnList(event);
- }
- }
- /**
- * *************************************************************
- * Appelle en GET la liste des utilisateurs et l'affiche dans la liste
- *
- * @param event ************************************************************
- */
- @FXML
- private void hBtnList(ActionEvent event) {
- ol.clear();
- try {
- final URL apiEndpoint = new URL(String.format("http://%s:%d/user/list", "localhost", ServiceAdminPort));
- // Preparer la connexion
- final HttpURLConnection connection = (HttpURLConnection) apiEndpoint.openConnection();
- try {
- // C'est une méthode GET
- connection.setRequestMethod("GET");
- } catch (ProtocolException ex) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
- }
- // Avec du contenu JSon
- connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
- connection.setDoInput(true);
- connection.setDoOutput(false);
- //code de la répose
- final int code = connection.getResponseCode();
- //afficher le code de la réponse
- // ol.add("RETOUR GET=" + code);
- //en fonction du code réponse
- switch (code) {
- case 200:
- case 201:
- //lire le corps de la réponse http => Json
- BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- StringBuilder sb = new StringBuilder();
- String line;
- while ((line = br.readLine()) != null) {
- sb.append(line).append("\n");
- }
- br.close();
- String json = sb.toString();
- //desencapsuler la réponse JSon
- Set<User> users = fromJSON(new TypeReference<Set<User>>() {
- }, json);
- TreeSet<User> usersSorted = new TreeSet(users);
- //afficher le contenu de l'objet
- for (User user : usersSorted) {
- ol.add(user.toString());
- }
- }
- } catch (MalformedURLException ex) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
- } catch (IOException ex) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
- ol.add("Le Web service GET ne répond pas !");
- }
- }
- /**
- * *************************************************************
- * Appeler le service GET et afficher le code retour et la réponse sous sa
- * forme JSon et sous sa forme desencapsulé.
- *
- * @param event ************************************************************
- */
- @FXML
- private void hBtnGeneratePDF(ActionEvent event) {
- ol.clear();
- try {
- final URL apiEndpoint = new URL(String.format("http://%s:%d/logs/get", "localhost", ServiceLogEditorPort));
- final HttpURLConnection connection = (HttpURLConnection) apiEndpoint.openConnection();
- try {
- connection.setRequestMethod("POST");
- } catch (ProtocolException ex) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
- }
- //spécifier que la connexion sera en entrée et sortie
- connection.setDoInput(true);
- connection.setDoOutput(true);
- String dateStartPost = dateStart.getValue().toString() + " 00:00:00";
- String dateEndPost = dateEnd.getValue().toString() + " 23:59:59";
- String data = "dateStart=" + URLEncoder.encode(dateStartPost, "UTF-8")
- + "&dateEnd=" + URLEncoder.encode(dateEndPost, "UTF-8");
- OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
- wr.write(data);
- wr.flush();
- //code de la répose
- final int code = connection.getResponseCode();
- //en fonction du code réponse
- switch (code) {
- case 200:
- case 201:
- //lire le corps de la réponse http => Json
- BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- StringBuilder sb = new StringBuilder();
- String line;
- while ((line = br.readLine()) != null) {
- sb.append(line).append("\n");
- }
- br.close();
- String json = sb.toString();
- //desencapsuler la réponse JSon
- Set<Log> logs = fromJSON(new TypeReference<Set<Log>>() {
- }, json);
- TreeSet<Log> logsSorted = new TreeSet(logs);
- //Creating PDF document object
- PDDocument document = new PDDocument();
- String title = "Messages envoyés entre le " + dateStartPost + " et le " + dateEndPost;
- //Creating a blank page
- PDPage blankPage = new PDPage();
- //Adding the blank page to the document
- document.addPage(blankPage);
- //Creating the PDDocumentInformation object
- PDDocumentInformation pdd = document.getDocumentInformation();
- pdd.setAuthor("Projet L3");
- pdd.setTitle(title);
- pdd.setCreator("Projet L3");
- pdd.setSubject(title);
- Calendar dateCal = new GregorianCalendar();
- pdd.setCreationDate(dateCal);
- //Saving the document
- DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
- Date date = new Date();
- File theDir = new File("logsPDF");
- if (!theDir.exists()) {
- try {
- theDir.mkdir();
- } catch (SecurityException se) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, se);
- }
- }
- PDPage page = document.getPage(0);
- PDPageContentStream contentStream = new PDPageContentStream(document, page);
- PDImageXObject pdImage = PDImageXObject.createFromFile("src/main/resources/images/istv.png", document);
- contentStream.drawImage(pdImage, 70, 650);
- PDImageXObject pdImage2 = PDImageXObject.createFromFile("src/main/resources/images/uvhc.jpg", document);
- contentStream.drawImage(pdImage2, 200, 650);
- contentStream.beginText();
- contentStream.setLeading(14.5f);
- contentStream.newLineAtOffset(50, 600);
- contentStream.setFont(PDType1Font.TIMES_ROMAN, 20);
- contentStream.showText(title);
- contentStream.newLine();
- contentStream.newLine();
- contentStream.setFont(PDType1Font.TIMES_ROMAN, 15);
- contentStream.showText("id sender_id receiver_id message date_send machine_sender machine_receiver;");
- contentStream.newLine();
- contentStream.newLine();
- contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);
- for (Log log : logsSorted) {
- contentStream.showText(log.toStringPDF());
- contentStream.newLine();
- }
- contentStream.endText();
- contentStream.close();
- document.save("logsPDF/msg_logs_" + dateFormat.format(date) + ".pdf");
- //Closing the document
- document.close();
- infoPDF.setText("PDF créé");
- infoPDF.setFill(Paint.valueOf("GREEN"));
- hBtnList(event);
- break;
- default:
- infoPDF.setText("Erreur SQL");
- infoPDF.setFill(Paint.valueOf("RED"));
- break;
- }
- } catch (MalformedURLException ex) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
- } catch (IOException ex) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
- infoPDF.setText("Erreur WebService");
- infoPDF.setFill(Paint.valueOf("RED"));
- }
- FadeTransition ft = new FadeTransition(Duration.millis(4000), infoPDF);
- ft.setFromValue(1.0);
- ft.setToValue(0);
- ft.play();
- }
- @FXML
- private void hBtnQuit(ActionEvent event) {
- Platform.exit();
- }
- /**
- * Désérialiser un JSON dans une liste
- *
- * @param <T>
- * @param type
- * @param jsonPacket
- * @return
- */
- public static <T> T fromJSON(final TypeReference<T> type,
- final String jsonPacket) {
- T data = null;
- try {
- data = new ObjectMapper().readValue(jsonPacket, type);
- } catch (Exception e) {
- Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, e);
- }
- return data;
- }
- }
Add Comment
Please, Sign In to add comment