From 1dc95fa604f5ae382e8d2331939a5e54d476868e Mon Sep 17 00:00:00 2001 From: "Notmoo-PC\\Notmoo" Date: Sat, 27 Jan 2018 18:58:01 +0100 Subject: [PATCH] [SERVEUR] Ajout des logs dans le projet serveur (log4j 2) --- Workspace/server/pom.xml | 17 +++++++ Workspace/server/server.iml | 3 ++ Workspace/server/src/main/WEB-INF/web.xml | 32 ++++++++++-- .../controller/SimpleMessageHandler.java | 10 +++- .../server/module/account/AccountService.java | 49 ++++++++++++++++--- .../server/module/account/FileAccountDao.java | 8 ++- .../server/module/account/IAccountDao.java | 4 +- .../server/module/client/ClientService.java | 11 +++-- .../pqt/server/module/sale/SaleService.java | 45 ++++++++++++----- .../module/statistics/StatisticsService.java | 7 ++- .../pqt/server/module/stock/StockService.java | 22 +++++---- .../com/pqt/server/servlets/QueryServlet.java | 31 ++++++++---- .../java/com/pqt/server/tools/FileUtil.java | 6 +++ .../tools/io/SimpleSerialFileManager.java | 28 +++++++++++ .../server/src/main/resources/log4j2.xml | 37 ++++++++++++++ 15 files changed, 260 insertions(+), 50 deletions(-) create mode 100644 Workspace/server/src/main/resources/log4j2.xml diff --git a/Workspace/server/pom.xml b/Workspace/server/pom.xml index 53fc9c3a..babdbf2b 100644 --- a/Workspace/server/pom.xml +++ b/Workspace/server/pom.xml @@ -32,6 +32,23 @@ 2.4 + + + org.apache.logging.log4j + log4j-api + 2.10.0 + + + org.apache.logging.log4j + log4j-core + 2.10.0 + + + org.apache.logging.log4j + log4j-web + 2.10.0 + + \ No newline at end of file diff --git a/Workspace/server/server.iml b/Workspace/server/server.iml index 4a7b9f5a..489f721d 100644 --- a/Workspace/server/server.iml +++ b/Workspace/server/server.iml @@ -29,5 +29,8 @@ + + + \ No newline at end of file diff --git a/Workspace/server/src/main/WEB-INF/web.xml b/Workspace/server/src/main/WEB-INF/web.xml index 0c9131ad..14814299 100644 --- a/Workspace/server/src/main/WEB-INF/web.xml +++ b/Workspace/server/src/main/WEB-INF/web.xml @@ -3,9 +3,35 @@ PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> - + - res-file.location - G:\temp\ + isLog4jAutoInitializationDisabled + true + + log4jContextName + pqt-server + + + + log4jServletFilter + org.apache.logging.log4j.web.Log4jServletFilter + + + + log4jServletFilter + /* + REQUEST + FORWARD + INCLUDE + ERROR + ASYNC + + + + org.apache.logging.log4j.web.Log4jServletContextListener + \ No newline at end of file diff --git a/Workspace/server/src/main/java/com/pqt/server/controller/SimpleMessageHandler.java b/Workspace/server/src/main/java/com/pqt/server/controller/SimpleMessageHandler.java index 8b6c278d..46c2337a 100644 --- a/Workspace/server/src/main/java/com/pqt/server/controller/SimpleMessageHandler.java +++ b/Workspace/server/src/main/java/com/pqt/server/controller/SimpleMessageHandler.java @@ -21,6 +21,8 @@ import com.pqt.server.module.statistics.StatisticsService; import com.pqt.server.module.stock.StockService; import com.pqt.server.tools.io.ISerialFileManager; import com.pqt.server.tools.io.SimpleSerialFileManagerFactory; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.*; @@ -52,6 +54,8 @@ import java.util.*; */ public class SimpleMessageHandler implements IMessageHandler { + private static Logger LOGGER = LogManager.getLogger(SimpleMessageHandler.class); + private final String header_ref_query = "Detail_refus"; private final String header_err_query = "Detail_erreur"; @@ -70,7 +74,8 @@ public class SimpleMessageHandler implements IMessageHandler { private MessageManager manager; public SimpleMessageHandler(String ressourceFolderPathStr) { - + LOGGER.info("Initialisation du gestionnaire de messages entrant"); + LOGGER.info("Emplacement des ressources du serveur : {}", ressourceFolderPathStr); serverStateService = new ServerStateService(); accountService = new AccountService(ressourceFolderPathStr); //clientService = new ClientService(); @@ -303,8 +308,10 @@ public class SimpleMessageHandler implements IMessageHandler { } private class MessageManager{ + private Set entries; + MessageManager(){ entries = new HashSet<>(); } @@ -314,6 +321,7 @@ public class SimpleMessageHandler implements IMessageHandler { } void support(MessageType type, IMessageProcess process, AccountLevel permissionLevel, boolean accountConnectionRequired){ + LOGGER.info("Ajout du support du type {} pour le niveau {} (connexion requise : {})", type.name(), permissionLevel.name(), accountConnectionRequired); entries.add(new MessageTypeEntry(type, process, permissionLevel, accountConnectionRequired)); } diff --git a/Workspace/server/src/main/java/com/pqt/server/module/account/AccountService.java b/Workspace/server/src/main/java/com/pqt/server/module/account/AccountService.java index 372cace3..c22abc01 100644 --- a/Workspace/server/src/main/java/com/pqt/server/module/account/AccountService.java +++ b/Workspace/server/src/main/java/com/pqt/server/module/account/AccountService.java @@ -3,8 +3,11 @@ package com.pqt.server.module.account; import com.pqt.core.entities.user_account.Account; import com.pqt.core.entities.user_account.AccountLevel; import com.pqt.core.entities.user_account.AccountUpdate; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.List; +import java.util.function.Predicate; //TODO Issue #6 : ajouter logs /** @@ -17,6 +20,8 @@ import java.util.List; */ public class AccountService { + private static Logger LOGGER = LogManager.getLogger(AccountService.class); + private IAccountDao dao; public AccountService(String ressourceFolderPathStr) { @@ -70,7 +75,9 @@ public class AccountService { * @return {@code true} si le changement d'état a eu lieu, {@code false} sinon. */ public boolean submitAccountCredentials(Account account, boolean desiredState) { - return dao.submitAccountCredentials(account, desiredState); + boolean status = dao.submitAccountCredentials(account, desiredState); + LOGGER.info("Changement d'état : compte '{}', état désiré '{}' --> résultat '{}'", account.getUsername(), desiredState, status); + return status; } /** @@ -120,18 +127,44 @@ public class AccountService { } public void applyUpdateList(List updates) { + Predicate predicate = update-> + (update.getOldVersion()!=null && dao.isAccountRegistered(update.getOldVersion())) + || update.getNewVersion()!=null; updates.stream() - .filter(update-> - (update.getOldVersion()!=null && dao.isAccountRegistered(update.getOldVersion())) - || update.getNewVersion()!=null) + .filter(predicate) .forEach(update->{ if(update.getNewVersion()==null){ - if(!dao.isAccountConnected(update.getOldVersion())) - dao.removeAccount(update.getOldVersion()); + if(!dao.isAccountConnected(update.getOldVersion())){ + if(dao.removeAccount(update.getOldVersion())) + LOGGER.info("Suppression du compte '{}'", update.getOldVersion().getUsername()); + else + LOGGER.info("Echec de la suppression du compte '{}'", + update.getOldVersion().getUsername()); + } }else if(update.getOldVersion()==null){ - dao.addAccount(update.getNewVersion()); + if(dao.addAccount(update.getNewVersion())) + LOGGER.info("Ajout du compte '{}'", update.getNewVersion().getUsername()); + else + LOGGER.info("Echec de l'ajout du compte '{}'", update.getNewVersion().getUsername()); }else{ - dao.modifyAccount(update.getOldVersion(), update.getNewVersion()); + if(dao.modifyAccount(update.getOldVersion(), update.getNewVersion())) + LOGGER.info("Modification du compte '{}'", update.getOldVersion().getUsername()); + else + LOGGER.info("Echec de la modification du compte '{}'", + update.getOldVersion().getUsername()); + } + }); + updates.stream() + .filter(predicate.negate()) + .forEach(update->{ + if(update.getOldVersion()!=null && update.getNewVersion()!=null){ + LOGGER.info("Modification du compte '{}' refusée : préconditions non-remplies", update.getOldVersion().getUsername()); + }else if(update.getOldVersion()!=null){ + LOGGER.info("Suppression du compte '{}' refusée : préconditions non-remplies", update.getOldVersion().getUsername()); + }else if(update.getNewVersion()!=null){ + LOGGER.info("Ajout du compte '{}' refusé : préconditions non-remplies", update.getNewVersion().getUsername()); + }else{ + LOGGER.info("Modification de compte refusée : ancienne et nouvelle version nulles", update.getOldVersion().getUsername()); } }); } diff --git a/Workspace/server/src/main/java/com/pqt/server/module/account/FileAccountDao.java b/Workspace/server/src/main/java/com/pqt/server/module/account/FileAccountDao.java index 8c27c88b..6c833cd7 100644 --- a/Workspace/server/src/main/java/com/pqt/server/module/account/FileAccountDao.java +++ b/Workspace/server/src/main/java/com/pqt/server/module/account/FileAccountDao.java @@ -169,16 +169,18 @@ public class FileAccountDao implements IAccountDao { } @Override - public synchronized void removeAccount(Account oldVersion) { + public synchronized boolean removeAccount(Account oldVersion) { AccountEntry match = lookupMatchingEntry(oldVersion, accountEntries); if(match!=null && !connectedAccount.contains(match)){ accountEntries.remove(match); saveToFile(); + return true; } + return false; } @Override - public synchronized void modifyAccount(Account oldVersion, Account newVersion) { + public synchronized boolean modifyAccount(Account oldVersion, Account newVersion) { AccountEntry match = lookupMatchingEntry(oldVersion, accountEntries); if(match!=null && oldVersion.getUsername().equals(newVersion.getUsername())){ boolean toReconnect = connectedAccount.remove(match); @@ -192,7 +194,9 @@ public class FileAccountDao implements IAccountDao { if(toReconnect) connectedAccount.add(newEntry); saveToFile(); + return true; } + return false; } /** diff --git a/Workspace/server/src/main/java/com/pqt/server/module/account/IAccountDao.java b/Workspace/server/src/main/java/com/pqt/server/module/account/IAccountDao.java index 03185abe..b51ab459 100644 --- a/Workspace/server/src/main/java/com/pqt/server/module/account/IAccountDao.java +++ b/Workspace/server/src/main/java/com/pqt/server/module/account/IAccountDao.java @@ -78,7 +78,7 @@ public interface IAccountDao { * * @param oldVersion */ - void removeAccount(Account oldVersion); + boolean removeAccount(Account oldVersion); /** * Modifie un objet {@link Account} {@code oldVersion} en remplaçant ses attributs par ceux de {@code newVersion}. @@ -89,5 +89,5 @@ public interface IAccountDao { * @param oldVersion * @param newVersion */ - void modifyAccount(Account oldVersion, Account newVersion); + boolean modifyAccount(Account oldVersion, Account newVersion); } diff --git a/Workspace/server/src/main/java/com/pqt/server/module/client/ClientService.java b/Workspace/server/src/main/java/com/pqt/server/module/client/ClientService.java index f05aec5a..7165c62f 100644 --- a/Workspace/server/src/main/java/com/pqt/server/module/client/ClientService.java +++ b/Workspace/server/src/main/java/com/pqt/server/module/client/ClientService.java @@ -1,6 +1,8 @@ package com.pqt.server.module.client; import com.pqt.core.entities.members.Client; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.Date; import java.util.HashSet; @@ -8,8 +10,6 @@ import java.util.List; import java.util.Set; import java.util.stream.Collectors; -//TODO Issue #6 : ajouter logs - /** * Cette classe correspond au service de gestion des clients. *

@@ -21,6 +21,8 @@ import java.util.stream.Collectors; */ public class ClientService { + private static Logger LOGGER = LogManager.getLogger(ClientService.class); + private Set clientCache; public ClientService(){ @@ -36,7 +38,7 @@ public class ClientService { * @return {@code true} si le client donné correspond à une entrée du cache, {@code false} sinon. */ public boolean isClientRegistered(Client client) { - return clientCache.contains(client); + return clientCache.contains(lookupClientEntry(client)); } /** @@ -46,8 +48,10 @@ public class ClientService { */ public void registerClient(Client client) { if(lookupClientEntry(client)==null){ + LOGGER.info("Ajout du client '{}' au cache", client.getAddress()); clientCache.add(new ClientEntry(client)); }else{ + LOGGER.debug("Rafraichissement du timestamp du client '{}'", client.getAddress()); refreshClientTimestamp(client); } } @@ -75,6 +79,7 @@ public class ClientService { * Vide le cache du service. */ public void clear(){ + LOGGER.info("Effaçage du cache client"); clientCache.clear(); } diff --git a/Workspace/server/src/main/java/com/pqt/server/module/sale/SaleService.java b/Workspace/server/src/main/java/com/pqt/server/module/sale/SaleService.java index e7bb3473..75ffdf4e 100644 --- a/Workspace/server/src/main/java/com/pqt/server/module/sale/SaleService.java +++ b/Workspace/server/src/main/java/com/pqt/server/module/sale/SaleService.java @@ -1,17 +1,13 @@ package com.pqt.server.module.sale; -import com.pqt.core.entities.product.Product; import com.pqt.core.entities.sale.LightweightSale; import com.pqt.core.entities.sale.Sale; import com.pqt.server.module.sale.listeners.ISaleFirerer; import com.pqt.server.module.sale.listeners.ISaleListener; import com.pqt.server.module.sale.listeners.SimpleSaleFirerer; import com.pqt.server.module.stock.StockService; - -import java.util.HashMap; -import java.util.Map; - -//TODO Issue #6 : ajouter logs +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Cette classe correspond au service de validation des commandes de produits. @@ -31,6 +27,8 @@ import java.util.Map; */ public class SaleService { + private static Logger LOGGER = LogManager.getLogger(SaleService.class); + private ISaleDao dao; private ISaleFirerer eventFirerer; @@ -48,7 +46,21 @@ public class SaleService { */ public long submitSale(Sale sale) { long id = dao.submitSale(sale); - if(id!=-1) eventFirerer.fireSaleValidatedEvent(sale); + if(id!=-1){ + LOGGER.info("Nouvelle commande : #{}, faite par '{}'(permission {}), de type '{}' et valant {}€", + id, + sale.getOrderedBy().getUsername(), + sale.getOrderedBy().getPermissionLevel().name(), + sale.getType().name(), + sale.getTotalPrice()); + eventFirerer.fireSaleValidatedEvent(sale); + }else{ + LOGGER.info("Refus d'une commande : faite par '{}'(permission {}), de type '{}' et valant {}€", + sale.getOrderedBy().getUsername(), + sale.getOrderedBy().getPermissionLevel().name(), + sale.getType().name(), + sale.getTotalPrice()); + } return id; } @@ -67,7 +79,13 @@ public class SaleService { Sale sale = dao.convert(lwSale); if(sale!=null) return submitSale(sale); - + else + LOGGER.info("Refus d'une lightweight commande : impossible de convertir en commande détaillée\n" + + "Faite par '{}'(premission {}), de type '{}' et valant {}€", + lwSale.getOrderedBy().getUsername(), + lwSale.getOrderedBy().getPermissionLevel().name(), + lwSale.getType().name(), + lwSale.getPrice()); return -1; } @@ -89,9 +107,14 @@ public class SaleService { * @return {@code true} si la commande a bel et bien été annulée, {@code false} si aucun changement n'a été fait. */ public boolean submitSaleRevert(long id) { - if(isSaleRevertSupported()) - return dao.submitSaleRevert(id); - else + if(isSaleRevertSupported()){ + boolean status = dao.submitSaleRevert(id); + if(status) + LOGGER.info("Revert de la commande #{}", id); + else + LOGGER.info("Echec du revert de la commande #{}", id); + return status; + }else throw new UnsupportedOperationException("Cette opération ('sale revert') n'est pas supportée par la configuration actuelle du serveur"); } diff --git a/Workspace/server/src/main/java/com/pqt/server/module/statistics/StatisticsService.java b/Workspace/server/src/main/java/com/pqt/server/module/statistics/StatisticsService.java index 8916893c..18e44a4c 100644 --- a/Workspace/server/src/main/java/com/pqt/server/module/statistics/StatisticsService.java +++ b/Workspace/server/src/main/java/com/pqt/server/module/statistics/StatisticsService.java @@ -6,19 +6,21 @@ import com.pqt.core.entities.sale.Sale; import com.pqt.server.module.sale.listeners.SaleListenerAdapter; import com.pqt.server.module.stock.StockService; import com.pqt.server.module.sale.SaleService; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; -//TODO Issue #6 : Ajouter logs - /** * Cette classe correspond au sservices de statistiques du serveur, chargé de calculer et de mettre à disposition * diverses données concernant les ventes effectuées et les produits vendus. */ public class StatisticsService { + private static Logger LOGGER = LogManager.getLogger(StatisticsService.class); + private StockService stockService; private int totalSaleAmount, staffSaleAmount, guestSaleAmount; @@ -39,6 +41,7 @@ public class StatisticsService { saleService.addListener(new SaleListenerAdapter() { @Override public void onSaleValidatedEvent(Sale sale) { + LOGGER.info("Mise à jour des statistiques suite à une vente"); double price = sale.getTotalPrice(), worth = sale.getTotalWorth(); totalSaleWorth+=worth; totalMoneyMade+=price; diff --git a/Workspace/server/src/main/java/com/pqt/server/module/stock/StockService.java b/Workspace/server/src/main/java/com/pqt/server/module/stock/StockService.java index 9e9734c6..9f04d8df 100644 --- a/Workspace/server/src/main/java/com/pqt/server/module/stock/StockService.java +++ b/Workspace/server/src/main/java/com/pqt/server/module/stock/StockService.java @@ -4,11 +4,11 @@ import com.pqt.core.entities.product.Product; import com.pqt.core.entities.product.ProductUpdate; import com.pqt.server.exception.ServerQueryException; import com.pqt.server.tools.entities.SaleContent; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.List; -//TODO Issue #6 : ajouter logs - /** * Cette classe correspond au service de gestion du stock de produits. Il est en charge de la persistance des * données liées aux produits, de founir un accès centralisé à ces données et se charge également d'appliquer les @@ -25,6 +25,8 @@ import java.util.List; */ public class StockService { + private static Logger LOGGER = LogManager.getLogger(StockService.class); + private IStockDao dao; public StockService(String ressourceFolderPathStr) { @@ -48,9 +50,9 @@ public class StockService { if(upd.getOldVersion()==null){ addProduct(upd.getNewVersion()); }else if(upd.getNewVersion()==null){ - removeProduct(upd.getOldVersion().getId()); + removeProduct(upd.getOldVersion()); }else if(upd.getOldVersion()!=null && upd.getNewVersion()!=null){ - modifyProduct(upd.getOldVersion().getId(), upd.getNewVersion()); + modifyProduct(upd.getOldVersion(), upd.getNewVersion()); }else{ throw new ServerQueryException("Object ProductUpdate invalide : old et new valent tous les deux null"); } @@ -58,14 +60,16 @@ public class StockService { } private void addProduct(Product product) { - dao.addProduct(product); + LOGGER.info("Ajout du produit '{}' --> id #{}", product.getName(), dao.addProduct(product)); } - private void removeProduct(long id) { - dao.removeProduct(id); + private void removeProduct(Product product) { + LOGGER.info("Suppression du produit #{} --> '{}'", product.getId(), product.getName()); + dao.removeProduct(product.getId()); } - private void modifyProduct(long id, Product product) { - dao.modifyProduct(id, product); + private void modifyProduct(Product oldVersion, Product newVersion) { + LOGGER.info("Modification du produit #{} --> '{}'", oldVersion.getId()); + dao.modifyProduct(oldVersion.getId(), newVersion); } } diff --git a/Workspace/server/src/main/java/com/pqt/server/servlets/QueryServlet.java b/Workspace/server/src/main/java/com/pqt/server/servlets/QueryServlet.java index 3f1484c2..a880365f 100644 --- a/Workspace/server/src/main/java/com/pqt/server/servlets/QueryServlet.java +++ b/Workspace/server/src/main/java/com/pqt/server/servlets/QueryServlet.java @@ -6,8 +6,8 @@ import com.pqt.core.entities.messages.Message; import com.pqt.server.controller.IMessageHandler; import com.pqt.server.controller.SimpleMessageHandler; import com.pqt.server.servlets.exceptions.BadPqtServerSetupException; -import com.pqt.server.tools.io.ISerialFileManager; -import com.pqt.server.tools.io.SimpleSerialFileManagerFactory; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; @@ -15,13 +15,13 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.URLDecoder; -//TODO Issue #6 : ajouter logs @WebServlet(name = "QueryServlet", urlPatterns = "/") public class QueryServlet extends HttpServlet { + private static Logger LOGGER = LogManager.getLogger(QueryServlet.class); + private IMessageToolFactory messageToolFactory; private IMessageHandler msgHandler; @@ -37,13 +37,15 @@ public class QueryServlet extends HttpServlet { executeServletProcess(request, response); } - private void executeServletProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + private void executeServletProcess(HttpServletRequest request, HttpServletResponse response) throws IOException { try { if (this.getServletContext().getRealPath("/WEB-INF/classes") == null) { response.getWriter().write(new BadPqtServerSetupException("Real path of ressource folder is null. Current PQT server only works with web server that unpack webapps' WAR files.").toString()); } else { - if (messageToolFactory == null) + if (messageToolFactory == null){ + LOGGER.debug("Initialisation de la fabrique de messages"); this.messageToolFactory = new GSonMessageToolFactory(); + } if (msgHandler == null) { /* @@ -54,26 +56,37 @@ public class QueryServlet extends HttpServlet { } if (request.getQueryString() != null && !request.getQueryString().isEmpty() && request.getParameter("message") != null) { try { + LOGGER.debug("Réception d'un message"); String messageToHandle; - if(request.getParameter("encode")!=null) + if(request.getParameter("encode")!=null){ + LOGGER.debug("Tentative de décodage du message ({})", request.getParameter("encode")); messageToHandle = URLDecoder.decode(request.getParameter("message"), request.getParameter("encode")); - else + }else messageToHandle = request.getParameter("message"); - Message resp = msgHandler.handleMessage(messageToolFactory.getObjectParser(Message.class).parse(request.getParameter("message"))); + Message msg = messageToolFactory.getObjectParser(Message.class).parse(messageToHandle); + + LOGGER.debug("Traitement du message (type : '{}', auteur : '{}')", msg.getType(), msg.getUser().getUsername()); + + Message resp = msgHandler.handleMessage(msg); + + LOGGER.debug("Envoi de la réponse (type : '{}')", resp.getType()); response.getWriter().write(messageToolFactory.getObjectFormatter(Message.class).format(resp)); } catch (Exception e) { + LOGGER.error("Exception durant le traitement du message : {}", e); e.printStackTrace(); response.getWriter().write(String.format("%s : %s", e.getClass().getName(), e.getMessage())); response.getWriter().write("StackTrace :"); e.printStackTrace(response.getWriter()); } } else { + LOGGER.error("Message reçu mais incorrectement construit"); response.getWriter().write("Query message was not correctly made : " + request.getQueryString()); } } }catch (Throwable e){ + LOGGER.error("Exception ou erreur durant l'exécution du processus du QueryServlet : {}", e); e.printStackTrace(); response.getWriter().write(e.toString()); } diff --git a/Workspace/server/src/main/java/com/pqt/server/tools/FileUtil.java b/Workspace/server/src/main/java/com/pqt/server/tools/FileUtil.java index e8292428..e9796803 100644 --- a/Workspace/server/src/main/java/com/pqt/server/tools/FileUtil.java +++ b/Workspace/server/src/main/java/com/pqt/server/tools/FileUtil.java @@ -1,5 +1,8 @@ package com.pqt.server.tools; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -7,6 +10,8 @@ import java.nio.file.Paths; public class FileUtil { + private static Logger LOGGER = LogManager.getLogger(FileUtil.class); + /** * @see #createFileIfNotExist(Path) */ @@ -24,6 +29,7 @@ public class FileUtil { */ public static boolean createFileIfNotExist(Path filePath) throws IOException { if(!FileUtil.exist(filePath)){ + LOGGER.debug("Création du ficher '{}'", filePath.toAbsolutePath().toString()); Files.createFile(filePath); return true; } diff --git a/Workspace/server/src/main/java/com/pqt/server/tools/io/SimpleSerialFileManager.java b/Workspace/server/src/main/java/com/pqt/server/tools/io/SimpleSerialFileManager.java index 5aea6ac2..2a0f44b2 100644 --- a/Workspace/server/src/main/java/com/pqt/server/tools/io/SimpleSerialFileManager.java +++ b/Workspace/server/src/main/java/com/pqt/server/tools/io/SimpleSerialFileManager.java @@ -1,6 +1,8 @@ package com.pqt.server.tools.io; import com.pqt.server.tools.FileUtil; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.*; import java.nio.file.Path; @@ -10,6 +12,8 @@ import java.util.*; //TODO vérifier que le save écrase bien le contenu précédent du fichier public class SimpleSerialFileManager implements ISerialFileManager { + private static Logger LOGGER = LogManager.getLogger(SimpleSerialFileManager.class); + private Path filePath; private Class clazz; @@ -18,11 +22,13 @@ public class SimpleSerialFileManager implements ISerialFileManager { } SimpleSerialFileManager(Path filePath, Class clazz){ + LOGGER.info("Gestionnaire de fichiers créé pour le fichier '{}'", filePath.toAbsolutePath().toString()); this.filePath = filePath; this.clazz = clazz; try{ FileUtil.createFileIfNotExist(filePath); }catch (IOException e){ + LOGGER.error("IOException durant la création d'un fichier : {}", e); e.printStackTrace(); } } @@ -31,11 +37,13 @@ public class SimpleSerialFileManager implements ISerialFileManager { public List loadListFromFile() { try{ if(!FileUtil.createFileIfNotExist(filePath)){ + LOGGER.debug("Chargement des données (liste) du fichier '{}'", filePath.toAbsolutePath().toString()); List loadedEntries = new ArrayList<>(); fillCollection(loadedEntries); return loadedEntries; } }catch(IOException | ClassNotFoundException e){ + onLoadError(e); e.printStackTrace(); } return new ArrayList<>(); @@ -45,11 +53,13 @@ public class SimpleSerialFileManager implements ISerialFileManager { public Set loadSetFromFile() { try{ if(!FileUtil.createFileIfNotExist(filePath)){ + LOGGER.debug("Chargement des données (set) du fichier '{}'", filePath.toAbsolutePath().toString()); Set loadedEntries = new HashSet<>(); fillCollection(loadedEntries); return loadedEntries; } }catch(IOException | ClassNotFoundException e){ + onLoadError(e); e.printStackTrace(); } return new HashSet<>(); @@ -88,21 +98,39 @@ public class SimpleSerialFileManager implements ISerialFileManager { try{ FileUtil.createFileIfNotExist(filePath); }catch (IOException e){ + onSaveError(e); e.printStackTrace(); return; } try(FileOutputStream fos = new FileOutputStream(filePath.toString()); ObjectOutputStream oos = new ObjectOutputStream(fos)){ + LOGGER.debug("Sauvegarde de données vers le fichier '{}'", filePath.toAbsolutePath().toString()); collection.forEach(p -> { try { oos.writeObject(p); } catch (IOException e) { + onSaveError(e); e.printStackTrace(); } }); }catch(IOException e){ + onSaveError(e); e.printStackTrace(); } } + + private void onLoadError(Throwable e){ + LOGGER.error("Exception durant le chargement des données du fichier '{}' : {} --> {}", + filePath.toAbsolutePath().toString(), + e.getClass().getName(), + e.getMessage()); + } + + private void onSaveError(Throwable e){ + LOGGER.error("Exception durant la sauvegarde de données vers le fichier '{}' : {} --> {}", + filePath.toAbsolutePath().toString(), + e.getClass().getName(), + e.getMessage()); + } } diff --git a/Workspace/server/src/main/resources/log4j2.xml b/Workspace/server/src/main/resources/log4j2.xml new file mode 100644 index 00000000..71a6df04 --- /dev/null +++ b/Workspace/server/src/main/resources/log4j2.xml @@ -0,0 +1,37 @@ + + + + PQT/logs/serveur-redux.log + PQT/logs/serveur-full.log + + + + + + + + + %d %p %C{1.} [%t] %m%n + + + + + %d %p %C{1.} [%t] %m%n + + + + + + + + + + + + + + + + + + \ No newline at end of file