TransactionManager.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */
  20. package org.openspcoop2.monitor.engine.transaction;

  21. import java.util.ArrayList;
  22. import java.util.HashMap;
  23. import java.util.List;
  24. import java.util.Map;

  25. import org.openspcoop2.core.commons.dao.DAOFactory;
  26. import org.openspcoop2.core.transazioni.DumpAllegato;
  27. import org.openspcoop2.core.transazioni.DumpContenuto;
  28. import org.openspcoop2.core.transazioni.DumpHeaderTrasporto;
  29. import org.openspcoop2.core.transazioni.DumpMessaggio;
  30. import org.openspcoop2.core.transazioni.IdDumpMessaggio;
  31. import org.openspcoop2.core.transazioni.Transazione;
  32. import org.openspcoop2.core.transazioni.constants.TipoMessaggio;
  33. import org.openspcoop2.core.transazioni.dao.IDumpMessaggioService;
  34. import org.openspcoop2.core.transazioni.dao.IDumpMessaggioServiceSearch;
  35. import org.openspcoop2.core.transazioni.dao.ITransazioneServiceSearch;
  36. import org.openspcoop2.generic_project.exception.NotFoundException;
  37. import org.openspcoop2.generic_project.expression.IExpression;
  38. import org.openspcoop2.generic_project.expression.IPaginatedExpression;
  39. import org.openspcoop2.monitor.sdk.constants.ContentResourceNames;
  40. import org.openspcoop2.monitor.sdk.constants.MessageType;
  41. import org.openspcoop2.monitor.sdk.constants.TransactionExceptionCode;
  42. import org.openspcoop2.monitor.sdk.exceptions.TransactionException;
  43. import org.openspcoop2.monitor.sdk.transaction.AbstractContentResource;
  44. import org.openspcoop2.monitor.sdk.transaction.Attachment;
  45. import org.openspcoop2.monitor.sdk.transaction.AttachmentResource;
  46. import org.openspcoop2.monitor.sdk.transaction.ContentResource;
  47. import org.openspcoop2.monitor.sdk.transaction.SOAPEnvelopeResource;
  48. import org.openspcoop2.monitor.sdk.transaction.Transaction;
  49. import org.openspcoop2.monitor.sdk.transaction.TransportHeaderResource;
  50. import org.openspcoop2.protocol.sdk.constants.RuoloMessaggio;
  51. import org.openspcoop2.protocol.sdk.diagnostica.DriverMsgDiagnosticiNotFoundException;
  52. import org.openspcoop2.protocol.sdk.diagnostica.FiltroRicercaDiagnosticiConPaginazione;
  53. import org.openspcoop2.protocol.sdk.diagnostica.IDiagnosticDriver;
  54. import org.openspcoop2.protocol.sdk.diagnostica.MsgDiagnostico;
  55. import org.openspcoop2.protocol.sdk.tracciamento.DriverTracciamentoNotFoundException;
  56. import org.openspcoop2.protocol.sdk.tracciamento.ITracciaDriver;
  57. import org.openspcoop2.protocol.sdk.tracciamento.Traccia;
  58. import org.openspcoop2.utils.date.DateManager;
  59. import org.slf4j.Logger;

  60. /**
  61.  * TransactionManager
  62.  *
  63.  * @author Poli Andrea (apoli@link.it)
  64.  * @author $Author$
  65.  * @version $Rev$, $Date$
  66.  */
  67. public class TransactionManager {

  68.     public static Transaction getTransaction(DAOFactory daoFactory, Logger log, String id, boolean debug)
  69.             throws TransactionException {
  70.        
  71.         Transaction transactionInfo = null;

  72.         ITracciaDriver driverTracciamento = null;
  73.         IDiagnosticDriver driverDiagnostici = null;
  74.         try {
  75.             org.openspcoop2.core.transazioni.dao.IServiceManager transazioniSM =
  76.                     (org.openspcoop2.core.transazioni.dao.IServiceManager) daoFactory.getServiceManager(org.openspcoop2.core.transazioni.utils.ProjectInfo.getInstance());
  77.             ITransazioneServiceSearch transazioniSearchDAO = transazioniSM.getTransazioneServiceSearch();

  78.             driverTracciamento = (ITracciaDriver)
  79.                     daoFactory.getServiceManager(org.openspcoop2.core.tracciamento.utils.ProjectInfo.getInstance());
  80.            
  81.             driverDiagnostici = (IDiagnosticDriver)
  82.                     daoFactory.getServiceManager(org.openspcoop2.core.diagnostica.utils.ProjectInfo.getInstance());
  83.            
  84.             // prelevo la transazione
  85.             IExpression exprFindTraccia = transazioniSearchDAO.newExpression();
  86.             exprFindTraccia.equals(Transazione.model().ID_TRANSAZIONE, id);
  87.             Transazione transazione = null;
  88.             try{
  89.                 transazione = transazioniSearchDAO.find(exprFindTraccia);
  90.                 transactionInfo = new Transaction(log,daoFactory,transazione);
  91.             }catch(NotFoundException notFound){
  92.                 log.info("Transazione con id ["+id+"] non trovata: "+notFound.getMessage(),notFound);
  93.                 throw new TransactionException(TransactionExceptionCode.NOT_FOUND,"Transazione con id ["+id+"] non trovata: "+notFound.getMessage(),notFound);
  94.             }
  95.                        
  96.             // tracce / diagnostici
  97.             Map<String, String> propertiesRicerca = new HashMap<>();
  98.            
  99.             propertiesRicerca.put("id_transazione", id);
  100.             Traccia tracciaRichiesta = null;
  101.             try{
  102.                 tracciaRichiesta = driverTracciamento.getTraccia(RuoloMessaggio.RICHIESTA, propertiesRicerca);
  103.                 transactionInfo.setRequestTrace(tracciaRichiesta);
  104.             }catch(DriverTracciamentoNotFoundException notFound){
  105.                 if(debug)
  106.                     log.debug("Traccia di richiesta non trovata per la transazione con id ["+id+"]: "+notFound.getMessage(),notFound);
  107.             }
  108.             Traccia tracciaRisposta = null;
  109.             try{
  110.                 tracciaRisposta = driverTracciamento.getTraccia(RuoloMessaggio.RISPOSTA, propertiesRicerca);
  111.                 transactionInfo.setResponseTrace(tracciaRisposta);
  112.             }catch(DriverTracciamentoNotFoundException notFound){
  113.                 if(debug)
  114.                     log.debug("Traccia di risposta non trovata per la transazione con id ["+id+"]: "+notFound.getMessage(),notFound);
  115.             }
  116.            
  117.             FiltroRicercaDiagnosticiConPaginazione filtro = new FiltroRicercaDiagnosticiConPaginazione();
  118.             filtro.setProperties(propertiesRicerca);
  119.             List<MsgDiagnostico> listDiagnostici = null;
  120.             try{
  121.                 listDiagnostici = driverDiagnostici.getMessaggiDiagnostici(filtro);
  122.                 transactionInfo.setMsgdiagnosticiList(listDiagnostici);
  123.             }catch(DriverMsgDiagnosticiNotFoundException notFound){
  124.                 if(debug)
  125.                     log.debug("Diagnostici non presenti per la transazione con id ["+id+"]: "+notFound.getMessage(),notFound);
  126.             }
  127.            
  128.             // risorse di contenuto
  129.             IDumpMessaggioServiceSearch dumpMessaggioSearchDAO = transazioniSM.getDumpMessaggioServiceSearch();
  130.             TransactionManager.retrieveContentResources(
  131.                         dumpMessaggioSearchDAO, transactionInfo);

  132.         } catch (Exception e) {
  133.             log.error(
  134.                     "TransactionManager.getTransaction(" + id
  135.                             + ") ha generato un errore: " + e.getMessage(), e);
  136.             throw new TransactionException(TransactionExceptionCode.GENERIC_ERROR,e.getMessage(),e);
  137.         }finally{
  138.             try{
  139.                 driverTracciamento.close();
  140.             }catch(Exception eClose){
  141.                 // close
  142.             }
  143.             try{
  144.                 driverDiagnostici.close();
  145.             }catch(Exception eClose){
  146.                 // close
  147.             }
  148.         }

  149.         return transactionInfo;
  150.     }

  151.    
  152.     public static void updateContentResources(Transaction transaction)
  153.             throws TransactionException {

  154.         // !AGGIORNA L'IMMAGINE PRESENTE SUL DATABASE!
  155.         // delle risorse NOME VALORE
  156.        
  157.         try {
  158.             List<ContentResource> resList = transaction.getContentResourcesByType(ContentResource.class);
  159.             if (resList.size() != 0) {
  160.                
  161.                 org.openspcoop2.core.transazioni.dao.IServiceManager transazioniSM =
  162.                         (org.openspcoop2.core.transazioni.dao.IServiceManager) transaction.getDAOFactory().getServiceManager(org.openspcoop2.core.transazioni.utils.ProjectInfo.getInstance());
  163.                 IDumpMessaggioService dumpMessaggioDAO = transazioniSM.getDumpMessaggioService();
  164.                 IDumpMessaggioServiceSearch dumpMessaggioSearchDAO = transazioniSM.getDumpMessaggioServiceSearch();

  165.                 IPaginatedExpression expr = dumpMessaggioSearchDAO.newPaginatedExpression();
  166.                 expr.
  167.                     limit(1000).
  168.                     equals(DumpMessaggio.model().ID_TRANSAZIONE,transaction.getIdTransazione());

  169.                 List<DumpMessaggio> list = dumpMessaggioSearchDAO.findAll(expr);

  170.                 // posso trovare 0/1/2 entries nella tabella dump_messaggi per
  171.                 // ogni transazione
  172.                 for (DumpMessaggio dumpMessaggio : list) {
  173.                    
  174.                     boolean update = updateResources(dumpMessaggio, transaction);

  175.                     // Se e' necessario aggiornare il database procedo.
  176.                     if (update) {
  177.                         IdDumpMessaggio idDumpMsg = new IdDumpMessaggio();
  178.                         idDumpMsg.setIdTransazione(transaction.getIdTransazione());
  179.                         idDumpMsg.setTipoMessaggio(dumpMessaggio.getTipoMessaggio());
  180.                         dumpMessaggioDAO.update(idDumpMsg, dumpMessaggio);
  181.                     }
  182.                 }
  183.            
  184.             }
  185.         } catch (Exception e) {
  186.             transaction.getLogger().error(
  187.                     "TransactionManager.updateContentResources() ha generato un errore: "
  188.                             + e.getMessage(), e);
  189.             throw new TransactionException(TransactionExceptionCode.GENERIC_ERROR,e.getMessage(),e);
  190.         }
  191.     }

  192.     public static boolean updateResources(DumpMessaggio dumpMessaggio, Transaction transaction) throws Exception{
  193.        
  194.         boolean update = false;
  195.        
  196.         List<ContentResource> resList = transaction.getContentResourcesByType(ContentResource.class);
  197.         if (resList.size() != 0) {
  198.        
  199.             // aggiorno i valori di proprieta' esistenti e rimuovo quelle presenti che non sono nella nuova immagine passata come parametro al metodo
  200.             List<DumpContenuto> lstContenuto = dumpMessaggio.getContenutoList();
  201.             for (DumpContenuto dumpContenuto : lstContenuto) {
  202.                 String resName = dumpContenuto.getNome();
  203.                 ContentResource resource = (ContentResource) transaction.getContentResourceByName(resName);
  204.                 if (resource != null) {
  205.                     //if(!resource.getValue().equals(dumpContenuto.getValore())){
  206.                     if(!resource.getValue().equals(TransactionContentUtils.getDumpContenutoValue(dumpContenuto))){
  207.                         TransactionContentUtils.setDumpContenutoValue(dumpContenuto, resource.getValue());
  208.                         update = true;
  209.                     }
  210.                 } else{
  211.                     lstContenuto.remove(dumpContenuto);
  212.                     update = true;
  213.                 }
  214.                 resList.remove(resource);
  215.             }
  216.    
  217.             // aggiungo le nuove proprieta' presenti nel parametro passato al metodo e non presenti su database
  218.             for (int i = 0; i < resList.size(); i++) {
  219.                 ContentResource cr = (ContentResource) resList.get(i);
  220.                 if(resList.get(i).getName()==null){
  221.                     throw new Exception("Trovata risorsa di contenuto senza nome");
  222.                 }
  223.                 if(resList.get(i).getValue()==null){
  224.                     throw new Exception("Trovata risorsa di contenuto con nome ["+resList.get(i).getName()+"] con valore non definito");
  225.                 }
  226.                 DumpContenuto c =
  227.                         TransactionContentUtils.createDumpContenuto(resList.get(i).getName(),
  228.                                 resList.get(i).getValue(),
  229.                                 DateManager.getDate());
  230.                 if(dumpMessaggio.getTipoMessaggio().equals(TipoMessaggio.RICHIESTA_INGRESSO) || dumpMessaggio.getTipoMessaggio().equals(TipoMessaggio.RICHIESTA_USCITA)){
  231.                     if(cr.isRequest()){
  232.                         dumpMessaggio.addContenuto(c);
  233.                         update = true;
  234.                     }
  235.                 }
  236.                 else{
  237.                     if(cr.isResponse()){
  238.                         dumpMessaggio.addContenuto(c);
  239.                         update = true;
  240.                     }
  241.                 }
  242.                
  243.             }
  244.            
  245.         }
  246.        
  247.        
  248.            
  249.         TransportHeaderResource resource = null;
  250.         if(TipoMessaggio.RICHIESTA_INGRESSO.equals(dumpMessaggio.getTipoMessaggio()) || TipoMessaggio.RICHIESTA_USCITA.equals(dumpMessaggio.getTipoMessaggio())){
  251.             resource = (TransportHeaderResource) transaction.getContentResourceByName(ContentResourceNames.REQ_TRANSPORT_HEADER);
  252.         }
  253.         else{
  254.             resource = (TransportHeaderResource) transaction.getContentResourceByName(ContentResourceNames.RES_TRANSPORT_HEADER);
  255.         }
  256.         List<String> keys = new ArrayList<>();
  257.         if(resource!=null && resource.keys()!=null && resource.keys().size()>0){
  258.             keys.addAll(resource.keys());
  259.         }
  260.        
  261.         // aggiorno i valori di proprieta' esistenti e rimuovo quelle presenti che non sono nella nuova immagine passata come parametro al metodo
  262.         List<DumpHeaderTrasporto> lstHeader = dumpMessaggio.getHeaderTrasportoList();
  263.         for (DumpHeaderTrasporto dumpHeader : lstHeader) {
  264.             String resName = dumpHeader.getNome();
  265.             if (resource != null) {
  266.                 String valore = resource.getProperty(resName);
  267.                 if(valore!=null){
  268.                     if(!dumpHeader.getValore().equals(valore)){
  269.                         dumpHeader.setValore(valore);  
  270.                         update = true;
  271.                     }
  272.                 } else{
  273.                     lstHeader.remove(dumpHeader);
  274.                     update = true;
  275.                 }
  276.             } else{
  277.                 lstHeader.remove(dumpHeader);
  278.                 update = true;
  279.             }
  280.             for (int i = 0; i < keys.size(); i++) {
  281.                 if(keys.get(i).equals(resName)){
  282.                     keys.remove(i);
  283.                     break;
  284.                 }
  285.             }
  286.         }

  287.         // aggiungo le nuove proprieta' presenti nel parametro passato al metodo e non presenti su database
  288.         for (int i = 0; i < keys.size(); i++) {
  289.             DumpHeaderTrasporto c = new DumpHeaderTrasporto();
  290.             if(keys.get(i)==null){
  291.                 throw new Exception("Trovato header di trasporto senza nome");
  292.             }
  293.             if(resource.getProperty(keys.get(i))==null){
  294.                 throw new Exception("Trovato header di trasporto con nome ["+keys.get(i)+"] con valore non definito");
  295.             }
  296.             c.setNome(keys.get(i));
  297.             c.setValore(resource.getProperty(keys.get(i)));
  298.             c.setDumpTimestamp(DateManager.getDate());
  299.             dumpMessaggio.addHeaderTrasporto(c);
  300.             update = true;
  301.         }
  302.        
  303.        
  304.        
  305.        
  306.        
  307.        
  308.         AttachmentResource attachResource = null;
  309.         if(TipoMessaggio.RICHIESTA_INGRESSO.equals(dumpMessaggio.getTipoMessaggio()) || TipoMessaggio.RICHIESTA_USCITA.equals(dumpMessaggio.getTipoMessaggio())){
  310.             attachResource = (AttachmentResource) transaction.getContentResourceByName(ContentResourceNames.REQ_ATTACHMENT);
  311.         }
  312.         else{
  313.             attachResource = (AttachmentResource) transaction.getContentResourceByName(ContentResourceNames.RES_ATTACHMENT);
  314.         }
  315.         List<String> cids = null;
  316.         if(attachResource!=null){
  317.             cids = attachResource.cids();
  318.         }
  319.        
  320.         // aggiorno i valori di proprieta' esistenti e rimuovo quelle presenti che non sono nella nuova immagine passata come parametro al metodo
  321.         List<DumpAllegato> lstAllegati = dumpMessaggio.getAllegatoList();
  322.         for (DumpAllegato dumpAllegato : lstAllegati) {
  323.             String cid = dumpAllegato.getContentId();
  324.             if (attachResource != null) {
  325.                 Attachment attach = attachResource.getAttachmentByContentId(cid);
  326.                 if(attach.isUpdated()){
  327.                     dumpAllegato.setContentType(attach.getContentType());
  328.                     dumpAllegato.setAllegato(attach.getContentAsByte());
  329.                     update = true;
  330.                 }
  331.             } else{
  332.                 lstAllegati.remove(dumpAllegato);
  333.                 update = true;
  334.             }
  335.             for (int i = 0; i < cids.size(); i++) {
  336.                 if(cids.get(i).equals(cid)){
  337.                     cids.remove(i);
  338.                     break;
  339.                 }
  340.             }
  341.         }

  342.         // aggiungo i nuovi attach presenti nel parametro passato al metodo e non presenti su database
  343.         if(cids!=null) {
  344.             for (int i = 0; i < cids.size(); i++) {
  345.                 Attachment attach = attachResource.getAttachmentByContentId(cids.get(i));
  346.                 DumpAllegato c = new DumpAllegato();
  347.                 c.setAllegato(attach.getContentAsByte());
  348.                 c.setContentId(attach.getContentID());
  349.                 c.setContentType(attach.getContentType());
  350.                 c.setDumpTimestamp(DateManager.getDate());
  351.                 dumpMessaggio.addAllegato(c);
  352.                 update = true;
  353.             }
  354.         }
  355.        
  356.        
  357.        
  358.         return update;      
  359.     }
  360.    
  361.     private static void addContentResource(Transaction transaction, AbstractContentResource res){
  362.         try {
  363.             transaction.addContentResource(res);
  364.         } catch (TransactionException e) {
  365.             if (TransactionExceptionCode.ADD_RES_EXIST.equals(e.getCode()) ) {
  366.                 transaction.getLogger().error(e.getMessage(),e);
  367.             } else {
  368.                 // si sta aggiungendo una risorsa giĆ  presente,
  369.                 try {
  370.                     transaction.updateContentResource(res);
  371.                 } catch (TransactionException e1) {
  372.                     transaction.getLogger().error(e1.getMessage(),e1);
  373.                 }
  374.             }
  375.         }
  376.     }
  377.    
  378.     private static void retrieveContentResources(
  379.             IDumpMessaggioServiceSearch dumpMessaggioSearchDAO,
  380.             Transaction transaction)  throws Exception{

  381.         IPaginatedExpression expr = dumpMessaggioSearchDAO.newPaginatedExpression();
  382.         expr.
  383.             limit(1000).
  384.             equals(DumpMessaggio.model().ID_TRANSAZIONE,
  385.                 transaction.getIdTransazione());

  386.         List<DumpMessaggio> list = dumpMessaggioSearchDAO.findAll(expr);

  387.         for (DumpMessaggio dumpMessaggio : list) {
  388.            
  389.             setContentResourcesInTransaction(transaction, dumpMessaggio);
  390.            
  391.         }



  392.     }
  393.    
  394.     public static void setContentResourcesInTransaction(Transaction transaction, DumpMessaggio dumpMessaggio){
  395.         MessageType tipoMessaggio = MessageType.valueOf(dumpMessaggio
  396.                 .getTipoMessaggioRawEnumValue());

  397.        
  398.         // **** SOAP ENVELOPE ****
  399.        
  400.         SOAPEnvelopeResource soapEnvelope = new SOAPEnvelopeResource(tipoMessaggio);
  401.         addContentResource(transaction, soapEnvelope);
  402.        
  403.        
  404.        
  405.        
  406.         // **** RISORSE NOME VALORE ****
  407.        
  408.         for (DumpContenuto dumpContenuto : dumpMessaggio.getContenutoList()) {
  409.                            
  410.             ContentResource res = new ContentResource(tipoMessaggio);
  411.             res.setName(dumpContenuto.getNome());
  412.             res.setValue(TransactionContentUtils.getDumpContenutoValue(dumpContenuto));

  413.             addContentResource(transaction, res);
  414.         }
  415.        
  416.        
  417.        
  418.         // **** HEADER HTTP *****
  419.        
  420.         TransportHeaderResource res = new TransportHeaderResource(tipoMessaggio);
  421.         for (DumpHeaderTrasporto dumpHeader : dumpMessaggio.getHeaderTrasportoList()) {
  422.             res.setProperty(dumpHeader.getNome(),dumpHeader.getValore());
  423.         }
  424.         addContentResource(transaction, res);
  425.        
  426.        
  427.        
  428.        
  429.         // **** ATTACHMENTS *****

  430.         AttachmentResource attRes = new AttachmentResource(tipoMessaggio);
  431.         for (DumpAllegato dumpAllegato : dumpMessaggio.getAllegatoList()) {
  432.             Attachment attach = new Attachment(
  433.                     dumpAllegato.getAllegato(),
  434.                     dumpAllegato.getContentId(),
  435.                     dumpAllegato.getContentType());

  436.             attRes.addAttachment(attach);
  437.         }
  438.         addContentResource(transaction, attRes);
  439.     }




  440. }