Guest User

Untitled

a guest
May 31st, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.98 KB | None | 0 0
  1. package com.projet.adminclient;
  2.  
  3. import com.fasterxml.jackson.core.type.TypeReference;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.google.gson.Gson;
  6. import java.io.BufferedReader;
  7. import java.io.File;
  8. import java.io.IOException;
  9. import java.io.InputStreamReader;
  10. import java.io.OutputStreamWriter;
  11. import java.net.HttpURLConnection;
  12. import java.net.MalformedURLException;
  13. import java.net.ProtocolException;
  14. import java.net.URL;
  15. import java.net.URLEncoder;
  16. import java.text.DateFormat;
  17. import java.text.SimpleDateFormat;
  18. import java.time.LocalDate;
  19. import java.time.format.DateTimeFormatter;
  20. import java.util.Calendar;
  21. import java.util.Date;
  22. import java.util.GregorianCalendar;
  23. import java.util.ResourceBundle;
  24. import java.util.Set;
  25. import java.util.TreeSet;
  26. import java.util.logging.Level;
  27. import java.util.logging.Logger;
  28. import java.util.regex.Matcher;
  29. import java.util.regex.Pattern;
  30. import javafx.animation.FadeTransition;
  31. import javafx.application.Platform;
  32. import javafx.collections.ObservableList;
  33. import javafx.event.ActionEvent;
  34. import javafx.fxml.FXML;
  35. import javafx.fxml.Initializable;
  36. import javafx.scene.control.Button;
  37. import javafx.scene.control.DatePicker;
  38. import javafx.scene.control.ListView;
  39. import javafx.scene.control.TextField;
  40. import javafx.scene.paint.Paint;
  41. import javafx.scene.text.Text;
  42. import javafx.util.Duration;
  43. import org.apache.pdfbox.pdmodel.PDDocument;
  44. import org.apache.pdfbox.pdmodel.PDDocumentInformation;
  45. import org.apache.pdfbox.pdmodel.PDPage;
  46. import org.apache.pdfbox.pdmodel.PDPageContentStream;
  47. import org.apache.pdfbox.pdmodel.font.PDType1Font;
  48. import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
  49.  
  50. public class FXMLController implements Initializable {
  51.  
  52. @FXML
  53. private Button btnCreate;
  54. @FXML
  55. private Button btnDelete;
  56. @FXML
  57. private Button btnList;
  58. @FXML
  59. private Button btnGeneratePDF;
  60. @FXML
  61. private ListView<String> lvUsers;
  62. @FXML
  63. private Button btnQuit;
  64. @FXML
  65. private TextField createPassword;
  66. @FXML
  67. private TextField createLogin;
  68. @FXML
  69. private Text infoCreate;
  70. @FXML
  71. private Text infoPDF;
  72. @FXML
  73. private DatePicker dateStart;
  74. @FXML
  75. private DatePicker dateEnd;
  76.  
  77. private final int ServiceAdminPort = 8085;
  78. private final int ServiceLogEditorPort = 8084;
  79.  
  80. //listView
  81. ObservableList<String> ol = javafx.collections.FXCollections.observableArrayList();
  82.  
  83. /**
  84. * **************************************
  85. * Appeler le Web service POST du BackEnd Afficher le code de retour du
  86. * service
  87. *
  88. * @param event **************************************
  89. */
  90. @FXML
  91. private void hBtnCreate(ActionEvent event) {
  92. try {
  93. //construire l'URL d'appel du service WS-R
  94. final URL apiEndpoint = new URL(String.format("http://%s:%d/user/create", "localhost", ServiceAdminPort));
  95.  
  96. // Preparer laconnection http
  97. final HttpURLConnection connection = (HttpURLConnection) apiEndpoint.openConnection();
  98. try {
  99. // Spécifier que c'est une methode POST
  100. connection.setRequestMethod("POST");
  101. } catch (ProtocolException ex) {
  102. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
  103. }
  104.  
  105. //spécifier que la connexion sera en entrée et sortie
  106. connection.setDoInput(true);
  107. connection.setDoOutput(true);
  108.  
  109. String data = "login=" + URLEncoder.encode(createLogin.getText(), "UTF-8")
  110. + "&password=" + URLEncoder.encode(createPassword.getText(), "UTF-8");
  111.  
  112. OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
  113. wr.write(data);
  114. wr.flush();
  115.  
  116. //récupérer le code de la réponse
  117. final int code = connection.getResponseCode();
  118.  
  119. //afficher le code de la réponse
  120. // ol.add("RETOUR GET=" + code);
  121. //en fonction du code réponse
  122. switch (code) {
  123. case 200:
  124. case 201:
  125. //lire le corps de la réponse http => Json
  126. BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  127. StringBuilder sb = new StringBuilder();
  128. String line;
  129. while ((line = br.readLine()) != null) {
  130. sb.append(line).append("\n");
  131. }
  132. br.close();
  133. String json = sb.toString();
  134. Reponse msg = new Gson().fromJson(sb.toString(), Reponse.class);
  135. infoCreate.setText(msg.getReponse());
  136. infoCreate.setFill(Paint.valueOf("GREEN"));
  137. hBtnList(event);
  138. break;
  139. default:
  140. infoCreate.setText("Erreur insertion");
  141. infoCreate.setFill(Paint.valueOf("RED"));
  142. break;
  143.  
  144. }
  145.  
  146. } catch (MalformedURLException ex) {
  147. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
  148. } catch (IOException ex) {
  149. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
  150. infoCreate.setText("Erreur WebService");
  151. infoCreate.setFill(Paint.valueOf("RED"));
  152. }
  153. FadeTransition ft = new FadeTransition(Duration.millis(4000), infoCreate);
  154. ft.setFromValue(1.0);
  155. ft.setToValue(0);
  156. ft.play();
  157. }
  158.  
  159. /**
  160. * ***************************
  161. * Initializer les objets du controller
  162. *
  163. * @param url
  164. * @param rb ***************************
  165. */
  166. @Override
  167. public void initialize(URL url, ResourceBundle rb) {
  168. //affecter l'ObservableList à la listView
  169. lvUsers.setItems(ol);
  170. String date = new SimpleDateFormat("dd-MM-yyyy").format(Calendar.getInstance().getTime());
  171. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
  172. LocalDate localDate = LocalDate.parse(date, formatter);
  173. dateStart.setValue(localDate);
  174. dateEnd.setValue(localDate);
  175.  
  176. hBtnList(null);
  177.  
  178. }
  179.  
  180. /**
  181. * **************************************
  182. * Appler le service DELETE et afficher le code retour du service
  183. *
  184. * @param event **************************************
  185. */
  186. @FXML
  187. private void hBtnDelete(ActionEvent event) {
  188. String string = lvUsers.getSelectionModel().getSelectedItem();
  189. System.out.println(string);
  190. Pattern pattern = Pattern.compile("^.*id=(\\d*).*");
  191. Matcher matcher = pattern.matcher(string);
  192. String id = null;
  193. while (matcher.find()) {
  194. id = matcher.group(1);
  195. }
  196. if (id != null) {
  197. ol.clear();
  198. try {
  199.  
  200. final URL apiEndpoint = new URL(String.format("http://%s:%d/user/delete/" + id, "localhost", ServiceAdminPort));
  201.  
  202. //construire l'URL d'appel du service WS-R
  203. final HttpURLConnection connection = (HttpURLConnection) apiEndpoint.openConnection();
  204. try {
  205. // C'est une methode DELETE
  206. connection.setRequestMethod("DELETE");
  207. } catch (ProtocolException ex) {
  208. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
  209. }
  210.  
  211. //spécifier que la connexion sera en entrée et sortie
  212. connection.setDoInput(true);
  213. connection.setDoOutput(true);
  214.  
  215. //recuperation code retour
  216. final int code = connection.getResponseCode();
  217.  
  218. //afficher code retour dasn la listView
  219. // ol.add("RETOUR DELETE=" + code);
  220. } catch (MalformedURLException ex) {
  221. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
  222. } catch (IOException ex) {
  223. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
  224. ol.add("Le Web service DELETE ne répond pas !");
  225. }
  226. hBtnList(event);
  227. }
  228. }
  229.  
  230. /**
  231. * *************************************************************
  232. * Appelle en GET la liste des utilisateurs et l'affiche dans la liste
  233. *
  234. * @param event ************************************************************
  235. */
  236. @FXML
  237. private void hBtnList(ActionEvent event) {
  238. ol.clear();
  239. try {
  240. final URL apiEndpoint = new URL(String.format("http://%s:%d/user/list", "localhost", ServiceAdminPort));
  241.  
  242. // Preparer la connexion
  243. final HttpURLConnection connection = (HttpURLConnection) apiEndpoint.openConnection();
  244. try {
  245. // C'est une méthode GET
  246. connection.setRequestMethod("GET");
  247. } catch (ProtocolException ex) {
  248. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
  249. }
  250. // Avec du contenu JSon
  251. connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
  252. connection.setDoInput(true);
  253. connection.setDoOutput(false);
  254.  
  255. //code de la répose
  256. final int code = connection.getResponseCode();
  257.  
  258. //afficher le code de la réponse
  259. // ol.add("RETOUR GET=" + code);
  260. //en fonction du code réponse
  261. switch (code) {
  262. case 200:
  263. case 201:
  264. //lire le corps de la réponse http => Json
  265. BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  266. StringBuilder sb = new StringBuilder();
  267. String line;
  268. while ((line = br.readLine()) != null) {
  269. sb.append(line).append("\n");
  270. }
  271. br.close();
  272. String json = sb.toString();
  273.  
  274. //desencapsuler la réponse JSon
  275. Set<User> users = fromJSON(new TypeReference<Set<User>>() {
  276. }, json);
  277. TreeSet<User> usersSorted = new TreeSet(users);
  278. //afficher le contenu de l'objet
  279. for (User user : usersSorted) {
  280. ol.add(user.toString());
  281. }
  282.  
  283. }
  284.  
  285. } catch (MalformedURLException ex) {
  286. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
  287. } catch (IOException ex) {
  288. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
  289. ol.add("Le Web service GET ne répond pas !");
  290. }
  291. }
  292.  
  293. /**
  294. * *************************************************************
  295. * Appeler le service GET et afficher le code retour et la réponse sous sa
  296. * forme JSon et sous sa forme desencapsulé.
  297. *
  298. * @param event ************************************************************
  299. */
  300. @FXML
  301. private void hBtnGeneratePDF(ActionEvent event) {
  302. ol.clear();
  303. try {
  304. final URL apiEndpoint = new URL(String.format("http://%s:%d/logs/get", "localhost", ServiceLogEditorPort));
  305.  
  306. final HttpURLConnection connection = (HttpURLConnection) apiEndpoint.openConnection();
  307. try {
  308. connection.setRequestMethod("POST");
  309. } catch (ProtocolException ex) {
  310. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
  311. }
  312. //spécifier que la connexion sera en entrée et sortie
  313. connection.setDoInput(true);
  314. connection.setDoOutput(true);
  315.  
  316. String dateStartPost = dateStart.getValue().toString() + " 00:00:00";
  317. String dateEndPost = dateEnd.getValue().toString() + " 23:59:59";
  318.  
  319. String data = "dateStart=" + URLEncoder.encode(dateStartPost, "UTF-8")
  320. + "&dateEnd=" + URLEncoder.encode(dateEndPost, "UTF-8");
  321.  
  322. OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
  323. wr.write(data);
  324. wr.flush();
  325.  
  326. //code de la répose
  327. final int code = connection.getResponseCode();
  328.  
  329. //en fonction du code réponse
  330. switch (code) {
  331. case 200:
  332. case 201:
  333. //lire le corps de la réponse http => Json
  334. BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  335. StringBuilder sb = new StringBuilder();
  336. String line;
  337. while ((line = br.readLine()) != null) {
  338. sb.append(line).append("\n");
  339. }
  340. br.close();
  341. String json = sb.toString();
  342.  
  343. //desencapsuler la réponse JSon
  344. Set<Log> logs = fromJSON(new TypeReference<Set<Log>>() {
  345. }, json);
  346. TreeSet<Log> logsSorted = new TreeSet(logs);
  347.  
  348. //Creating PDF document object
  349. PDDocument document = new PDDocument();
  350. String title = "Messages envoyés entre le " + dateStartPost + " et le " + dateEndPost;
  351. //Creating a blank page
  352. PDPage blankPage = new PDPage();
  353.  
  354. //Adding the blank page to the document
  355. document.addPage(blankPage);
  356.  
  357. //Creating the PDDocumentInformation object
  358. PDDocumentInformation pdd = document.getDocumentInformation();
  359. pdd.setAuthor("Projet L3");
  360. pdd.setTitle(title);
  361. pdd.setCreator("Projet L3");
  362. pdd.setSubject(title);
  363. Calendar dateCal = new GregorianCalendar();
  364. pdd.setCreationDate(dateCal);
  365.  
  366. //Saving the document
  367. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
  368. Date date = new Date();
  369.  
  370. File theDir = new File("logsPDF");
  371. if (!theDir.exists()) {
  372. try {
  373. theDir.mkdir();
  374. } catch (SecurityException se) {
  375. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, se);
  376. }
  377. }
  378.  
  379. PDPage page = document.getPage(0);
  380. PDPageContentStream contentStream = new PDPageContentStream(document, page);
  381.  
  382. PDImageXObject pdImage = PDImageXObject.createFromFile("src/main/resources/images/istv.png", document);
  383. contentStream.drawImage(pdImage, 70, 650);
  384. PDImageXObject pdImage2 = PDImageXObject.createFromFile("src/main/resources/images/uvhc.jpg", document);
  385. contentStream.drawImage(pdImage2, 200, 650);
  386.  
  387. contentStream.beginText();
  388. contentStream.setLeading(14.5f);
  389.  
  390. contentStream.newLineAtOffset(50, 600);
  391. contentStream.setFont(PDType1Font.TIMES_ROMAN, 20);
  392. contentStream.showText(title);
  393. contentStream.newLine();
  394. contentStream.newLine();
  395.  
  396. contentStream.setFont(PDType1Font.TIMES_ROMAN, 15);
  397. contentStream.showText("id sender_id receiver_id message date_send machine_sender machine_receiver;");
  398. contentStream.newLine();
  399. contentStream.newLine();
  400. contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);
  401. for (Log log : logsSorted) {
  402. contentStream.showText(log.toStringPDF());
  403. contentStream.newLine();
  404. }
  405.  
  406. contentStream.endText();
  407. contentStream.close();
  408.  
  409. document.save("logsPDF/msg_logs_" + dateFormat.format(date) + ".pdf");
  410.  
  411. //Closing the document
  412. document.close();
  413.  
  414. infoPDF.setText("PDF créé");
  415. infoPDF.setFill(Paint.valueOf("GREEN"));
  416. hBtnList(event);
  417. break;
  418. default:
  419. infoPDF.setText("Erreur SQL");
  420. infoPDF.setFill(Paint.valueOf("RED"));
  421. break;
  422.  
  423. }
  424.  
  425. } catch (MalformedURLException ex) {
  426. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
  427. } catch (IOException ex) {
  428. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
  429. infoPDF.setText("Erreur WebService");
  430. infoPDF.setFill(Paint.valueOf("RED"));
  431. }
  432.  
  433. FadeTransition ft = new FadeTransition(Duration.millis(4000), infoPDF);
  434. ft.setFromValue(1.0);
  435. ft.setToValue(0);
  436. ft.play();
  437. }
  438.  
  439. @FXML
  440. private void hBtnQuit(ActionEvent event) {
  441. Platform.exit();
  442. }
  443.  
  444. /**
  445. * Désérialiser un JSON dans une liste
  446. *
  447. * @param <T>
  448. * @param type
  449. * @param jsonPacket
  450. * @return
  451. */
  452. public static <T> T fromJSON(final TypeReference<T> type,
  453. final String jsonPacket) {
  454. T data = null;
  455.  
  456. try {
  457. data = new ObjectMapper().readValue(jsonPacket, type);
  458. } catch (Exception e) {
  459. Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, e);
  460. }
  461. return data;
  462. }
  463. }
Add Comment
Please, Sign In to add comment