SavedMessagePSUtilities.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.pdd.core;

  21. import java.io.ByteArrayOutputStream;
  22. import java.io.IOException;
  23. import java.io.Serializable;
  24. import java.sql.Connection;
  25. import java.sql.PreparedStatement;
  26. import java.sql.SQLException;
  27. import java.sql.Timestamp;

  28. import org.openspcoop2.message.OpenSPCoop2Message;
  29. import org.openspcoop2.message.constants.MessageType;
  30. import org.openspcoop2.message.constants.ServiceBinding;
  31. import org.openspcoop2.message.context.SerializedContext;
  32. import org.openspcoop2.message.context.SerializedParameter;
  33. import org.openspcoop2.message.exception.MessageException;
  34. import org.openspcoop2.message.exception.MessageNotSupportedException;
  35. import org.openspcoop2.pdd.core.state.OpenSPCoopStateless;
  36. import org.openspcoop2.protocol.engine.constants.Costanti;
  37. import org.openspcoop2.protocol.sdk.Context;
  38. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  39. import org.openspcoop2.protocol.sdk.state.RequestInfoConfigUtilities;
  40. import org.openspcoop2.protocol.sdk.state.StateMessage;
  41. import org.openspcoop2.utils.MapKey;
  42. import org.openspcoop2.utils.UtilsException;
  43. import org.openspcoop2.utils.beans.WriteToSerializerType;
  44. import org.openspcoop2.utils.serialization.JavaSerializer;


  45. /**
  46.  * SavedMessagePSUtilities
  47.  *
  48.  * @author Poli Andrea (apoli@link.it)
  49.  * @author Tronci Fabio (tronci@link.it)
  50.  * @author Lorenzo Nardi (nardi@link.it)
  51.  * @author $Author$
  52.  * @version $Rev$, $Date$
  53.  */



  54. public class SavedMessagePSUtilities {
  55.    
  56.     private SavedMessagePSUtilities() {}

  57.     public static void save(SavedMessage savedMessage,
  58.             OpenSPCoop2Message msg, boolean isRichiesta, boolean portaDiTipoStateless, boolean consumeMessage, Timestamp oraRegistrazione) throws UtilsException{

  59.         if( !portaDiTipoStateless ) {
  60.             StateMessage stateMsg = (isRichiesta) ?  
  61.                     (StateMessage)savedMessage.openspcoopstate.getStatoRichiesta() :
  62.                         (StateMessage)savedMessage.openspcoopstate.getStatoRisposta();
  63.             Connection connectionDB = stateMsg.getConnectionDB();

  64.             saveStateful(savedMessage,
  65.                     msg, consumeMessage, oraRegistrazione,
  66.                     connectionDB, stateMsg);
  67.            
  68.         }else { /** if (portaDiTipoStateless){ */

  69.             if (isRichiesta) ((OpenSPCoopStateless)savedMessage.openspcoopstate).setRichiestaMsg(msg);
  70.             else ((OpenSPCoopStateless)savedMessage.openspcoopstate).setRispostaMsg(msg);


  71.         }

  72.     }  
  73.    
  74.     private static void saveStateful(SavedMessage savedMessage,
  75.             OpenSPCoop2Message msg, boolean consumeMessage, Timestamp oraRegistrazione,
  76.             Connection connectionDB, StateMessage stateMsg) throws UtilsException {
  77.         PreparedStatement pstmt = null;
  78.         try{
  79.             // Save proprieta' msg
  80.             StringBuilder query = new StringBuilder();
  81.             query.append("INSERT INTO  ");
  82.             query.append(GestoreMessaggi.DEFINIZIONE_MESSAGGI);
  83.             if(savedMessage.saveOnFS)
  84.                 query.append(" (ID_MESSAGGIO,TIPO,CONTENT_TYPE,ORA_REGISTRAZIONE) VALUES ( ? , ? , ? , ? )");
  85.             else
  86.                 query.append(" (ID_MESSAGGIO,TIPO,CONTENT_TYPE,ORA_REGISTRAZIONE,MSG_BYTES,MSG_CONTEXT) VALUES ( ? , ? , ? , ? , ? , ?)");

  87.             pstmt = connectionDB.prepareStatement(query.toString());
  88.             pstmt.setString(1,savedMessage.idMessaggio);
  89.             if(Costanti.INBOX.equals(savedMessage.box))
  90.                 pstmt.setString(2,Costanti.INBOX);
  91.             else
  92.                 pstmt.setString(2,Costanti.OUTBOX);    

  93.             //Sposto il set del contentType dopo la writeTo del messaggio
  94.             //cosi nel caso di attachment lo trovo corretto.

  95.             saveNormalizeRequestInfoBeforeSerialization(savedMessage,
  96.                     msg, consumeMessage,
  97.                     pstmt);

  98.             // Set del contentType nella query
  99.             String contentType = readContentType(msg);
  100.             pstmt.setString(3,contentType);
  101.            
  102.             // Set Ora Registrazione
  103.             pstmt.setTimestamp(4,oraRegistrazione);

  104.             // Add PreparedStatement
  105.             stateMsg.getPreparedStatement().put("INSERT (MSG_OP_STEP1a) saveMessage["+savedMessage.idMessaggio+","+savedMessage.box+"]",pstmt);

  106.         }catch(Exception e){
  107.             try{
  108.                 if( pstmt != null )
  109.                     pstmt.close();
  110.             } catch(Exception err) {
  111.                 // close
  112.             }
  113.             String errorMsg = "SOAP_MESSAGE, save : "+savedMessage.box+"/"+savedMessage.idMessaggio+": "+e.getMessage();        
  114.             savedMessage.logError(errorMsg,e);
  115.             throw new UtilsException(errorMsg,e);
  116.         }
  117.     }
  118.    
  119.     private static void saveNormalizeRequestInfoBeforeSerialization(SavedMessage savedMessage,
  120.             OpenSPCoop2Message msg, boolean consumeMessage,
  121.             PreparedStatement pstmt) throws UtilsException, MessageException, IOException, SQLException {
  122.         // Elimino dalla RequestInfo i dati "cached"
  123.         RequestInfo requestInfoBackup = RequestInfoConfigUtilities.normalizeRequestInfoBeforeSerialization(msg);
  124.         try {
  125.             save(savedMessage,
  126.                     msg, consumeMessage,
  127.                     pstmt);
  128.         }finally {
  129.             if(requestInfoBackup!=null) {
  130.                 RequestInfoConfigUtilities.restoreRequestInfoAfterSerialization(msg, requestInfoBackup);
  131.             }
  132.         }
  133.     }
  134.     private static void save(SavedMessage savedMessage,
  135.             OpenSPCoop2Message msg, boolean consumeMessage,
  136.             PreparedStatement pstmt) throws UtilsException, MessageException, IOException, SQLException {
  137.         if(savedMessage.saveOnFS){
  138.             // SAVE IN FILE SYSTEM
  139.            
  140.             String saveDir = savedMessage.getBaseDir();
  141.             savedMessage.checkInizializzazioneWorkingDir(saveDir);
  142.            
  143.             // Save bytes message
  144.             String pathBytes = saveDir + savedMessage.keyMsgBytes;
  145.             savedMessage.saveMessageBytes(pathBytes,msg, consumeMessage,false);
  146.            
  147.             // Save message context
  148.             String pathContext = saveDir + savedMessage.keyMsgContext;
  149.             savedMessage.saveMessageContext(pathContext,msg,false);
  150.            
  151.         }else{
  152.             // SAVE IN DB
  153.            
  154.             // Save bytes message
  155.             java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
  156.             msg.writeTo(bout,consumeMessage);
  157.             bout.flush();
  158.             bout.close();
  159.             /** System.out.println("---------SALVO RISPOSTA: "+msgByte.toString()); */
  160.             savedMessage.adapter.setBinaryData(pstmt,5,bout.toByteArray());
  161.            
  162.             // Save message context
  163.             bout = new java.io.ByteArrayOutputStream();
  164.             msg.serializeResourcesTo(bout);
  165.             bout.flush();
  166.             bout.close();
  167.             /** System.out.println("---------SALVO CONTEXT: "+msgByte.toString()); */
  168.             savedMessage.adapter.setBinaryData(pstmt,6,bout.toByteArray());
  169.         }
  170.     }
  171.     private static String readContentType(OpenSPCoop2Message msg) throws UtilsException, MessageException, MessageNotSupportedException {
  172.        
  173.         String prefix = "Rilevata una richiesta "+msg.getServiceBinding();
  174.        
  175.         String contentType = msg.getContentType();
  176.         if(contentType==null || "".equals(contentType)){
  177.             if(ServiceBinding.REST.equals(msg.getServiceBinding())){
  178.                 if(MessageType.BINARY.equals(msg.getMessageType())) {
  179.                     if(msg.castAsRest().hasContent()) {
  180.                         throw new UtilsException(prefix+" "+msg.getMessageType()+" con payload per la quale non è stato fornito un ContentType"); // sul DB e' required la colonna
  181.                     }
  182.                     else {
  183.                         contentType = SavedMessage.REST_CONTENT_TYPE_EMPTY;
  184.                     }
  185.                 }
  186.                 else {
  187.                     throw new UtilsException(prefix+" "+msg.getMessageType()+" per la quale non è stato fornito un ContentType"); // sul DB e' required la colonna
  188.                 }
  189.             }
  190.             else {
  191.                 throw new UtilsException(prefix+" per la quale non è stato fornito un ContentType"); // sul DB e' required la colonna
  192.             }
  193.         }
  194.         return contentType;
  195.     }

  196.    
  197.     public static void updateResponse(SavedMessage savedMessage,
  198.             OpenSPCoop2Message msg, boolean consumeMessage) throws UtilsException{

  199.         StateMessage stateMsg = (StateMessage)savedMessage.openspcoopstate.getStatoRisposta();
  200.         Connection connectionDB = stateMsg.getConnectionDB();

  201.         PreparedStatement pstmt = null;
  202.         try{
  203.             // Save proprieta' msg
  204.             StringBuilder query = new StringBuilder();
  205.             query.append("UPDATE ");
  206.             query.append(GestoreMessaggi.DEFINIZIONE_MESSAGGI);
  207.             query.append(" SET ");
  208.             query.append(" RESPONSE_CONTENT_TYPE=? ");
  209.             if(!savedMessage.saveOnFS) {
  210.                 query.append(" , RESPONSE_MSG_BYTES=? ");
  211.                 query.append(" , RESPONSE_MSG_CONTEXT=? ");
  212.             }
  213.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");


  214.             pstmt = connectionDB.prepareStatement(query.toString());
  215.             int index = 1;
  216.            
  217.             // Set del contentType nella query
  218.             String contentType = readContentType(msg);
  219.             pstmt.setString(index++,contentType);
  220.            
  221.             index = updateResponseNormalizeRequestInfoBeforeSerialization(savedMessage,
  222.                     msg, consumeMessage,
  223.                     pstmt, index);
  224.            
  225.             pstmt.setString(index++,savedMessage.idMessaggio);
  226.             if(Costanti.INBOX.equals(savedMessage.box))
  227.                 pstmt.setString(index,Costanti.INBOX);
  228.             else
  229.                 pstmt.setString(index,Costanti.OUTBOX);    


  230.             // Add PreparedStatement
  231.             stateMsg.getPreparedStatement().put("UPDATE (RESPONSE) saveMessage["+savedMessage.idMessaggio+","+savedMessage.box+"]",pstmt);
  232.    
  233.         }catch(Exception e){
  234.             try{
  235.                 if( pstmt != null )
  236.                     pstmt.close();
  237.             } catch(Exception err) {
  238.                 // close
  239.             }
  240.             String errorMsg = "SOAP_MESSAGE, update response : "+savedMessage.box+"/"+savedMessage.idMessaggio+": "+e.getMessage();    
  241.             savedMessage.logError(errorMsg,e);
  242.             throw new UtilsException(errorMsg,e);
  243.         }

  244.     }    
  245.    
  246.     private static int updateResponseNormalizeRequestInfoBeforeSerialization(SavedMessage savedMessage,
  247.             OpenSPCoop2Message msg, boolean consumeMessage,
  248.             PreparedStatement pstmt, int index) throws UtilsException, MessageException, IOException, SQLException {
  249.         // Elimino dalla RequestInfo i dati "cached"
  250.         RequestInfo requestInfoBackup = RequestInfoConfigUtilities.normalizeRequestInfoBeforeSerialization(msg);
  251.         try {
  252.             return updateResponse(savedMessage,
  253.                     msg, consumeMessage,
  254.                     pstmt, index);
  255.         }finally {
  256.             if(requestInfoBackup!=null) {
  257.                 RequestInfoConfigUtilities.restoreRequestInfoAfterSerialization(msg, requestInfoBackup);
  258.             }
  259.         }
  260.     }
  261.     private static int updateResponse(SavedMessage savedMessage,
  262.             OpenSPCoop2Message msg, boolean consumeMessage,
  263.             PreparedStatement pstmt, int index) throws UtilsException, MessageException, IOException, SQLException {
  264.         if(savedMessage.saveOnFS){
  265.             // SAVE IN FILE SYSTEM
  266.            
  267.             String saveDir = savedMessage.getBaseDir();
  268.             savedMessage.checkInizializzazioneWorkingDir(saveDir);
  269.            
  270.             // Save bytes message
  271.             String pathBytes = saveDir + savedMessage.keyMsgResponseBytes;
  272.             savedMessage.saveMessageBytes(pathBytes,msg, consumeMessage, false);
  273.            
  274.             // Save message context
  275.             String pathContext = saveDir + savedMessage.keyMsgResponseContext;
  276.             savedMessage.saveMessageContext(pathContext,msg, false);
  277.            
  278.         }else{
  279.             // SAVE IN DB
  280.            
  281.             // Save bytes message
  282.             java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
  283.             msg.writeTo(bout,consumeMessage);
  284.             bout.flush();
  285.             bout.close();
  286.             /** System.out.println("---------SALVO RISPOSTA: "+msgByte.toString()); */
  287.             savedMessage.adapter.setBinaryData(pstmt,index++,bout.toByteArray());
  288.            
  289.             // Save message context
  290.             bout = new java.io.ByteArrayOutputStream();
  291.             msg.serializeResourcesTo(bout);
  292.             bout.flush();
  293.             bout.close();
  294.             /** System.out.println("---------SALVO CONTEXT: "+msgByte.toString()); */
  295.             savedMessage.adapter.setBinaryData(pstmt,index++,bout.toByteArray());
  296.         }
  297.         return index;
  298.     }
  299.    
  300.    
  301.    
  302.    
  303.    
  304.    
  305.    
  306.     public static void updateTransactionContext(SavedMessage savedMessage,Context transactionContext) throws UtilsException{

  307.         if(transactionContext==null || transactionContext.isEmpty()) {
  308.             return;
  309.         }
  310.        
  311.         SerializedContext sc = buildSerializedContext(transactionContext);
  312.        
  313.         if(savedMessage.saveOnFS) {
  314.            
  315.             String saveDir = savedMessage.getBaseDir();
  316.             savedMessage.checkInizializzazioneWorkingDir(saveDir);
  317.            
  318.             // Save bytes message
  319.             String pathBytes = saveDir + savedMessage.keyMsgTransactionContext;
  320.             savedMessage.saveTransactionContext(pathBytes,sc, false);
  321.            
  322.         }
  323.         else {
  324.        
  325.             StateMessage stateMsg = (StateMessage)savedMessage.openspcoopstate.getStatoRisposta();
  326.             Connection connectionDB = stateMsg.getConnectionDB();
  327.    
  328.             // Save proprieta' msg
  329.             StringBuilder query = new StringBuilder();
  330.             query.append("UPDATE ");
  331.             query.append(GestoreMessaggi.DEFINIZIONE_MESSAGGI);
  332.             query.append(" SET ");
  333.             query.append(" TRANSACTION_CONTEXT=? ");
  334.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");
  335.            
  336.             try (PreparedStatement pstmt = connectionDB.prepareStatement(query.toString());){
  337.                 int index = 1;
  338.                
  339.                 java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
  340.                 sc.writeTo(bout, WriteToSerializerType.XML_JAXB);
  341.                 bout.flush();
  342.                 bout.close();
  343.                
  344.                 /** System.out.println("---------SALVO TRANSACTION CONTEXT: "+msgByte.toString()); */
  345.                 savedMessage.adapter.setBinaryData(pstmt,index++,bout.toByteArray());
  346.                
  347.                 pstmt.setString(index++,savedMessage.idMessaggio);
  348.                 if(Costanti.INBOX.equals(savedMessage.box))
  349.                     pstmt.setString(index,Costanti.INBOX);
  350.                 else
  351.                     pstmt.setString(index,Costanti.OUTBOX);    
  352.                
  353.                 pstmt.executeUpdate();
  354.        
  355.             }catch(Exception e){
  356.                 String errorMsg = "SOAP_MESSAGE, update transaction context : "+savedMessage.box+"/"+savedMessage.idMessaggio+": "+e.getMessage();      
  357.                 savedMessage.logError(errorMsg,e);
  358.                 throw new UtilsException(errorMsg,e);
  359.             }
  360.            
  361.         }

  362.     }  
  363.     private static SerializedContext buildSerializedContext(Context transactionContext) throws UtilsException{
  364.        
  365.         try {
  366.        
  367.             SerializedContext sc = new SerializedContext();
  368.             JavaSerializer jSerializer = new JavaSerializer();
  369.             for (MapKey<String> key : transactionContext.keySet()) {
  370.                 Object o = transactionContext.get(key);
  371.                 if(!CostantiPdD.SALVA_CONTESTO_IDENTIFICATIVO_MESSAGGIO_NOTIFICA.equals(key) &&
  372.                         (o instanceof Serializable)
  373.                         ) {
  374.                     SerializedParameter p = new SerializedParameter();
  375.                     p.setNome(key.getValue());
  376.                     p.setClasse(o.getClass().getName());
  377.                     ByteArrayOutputStream bout = new ByteArrayOutputStream();
  378.                     jSerialize(jSerializer, o, bout, p);
  379.                     bout.flush();
  380.                     bout.close();
  381.                     p.setBase(bout.toByteArray());
  382.                     sc.addProperty(p);
  383.                 }
  384.             }
  385.             return sc;
  386.            
  387.         }catch(Exception e){
  388.             throw new UtilsException(e.getMessage(),e);
  389.         }
  390.     }
  391.     private static void jSerialize(JavaSerializer jSerializer, Object o, ByteArrayOutputStream bout, SerializedParameter p) throws UtilsException {
  392.         try {
  393.             jSerializer.writeObject(o, bout);
  394.         }catch(Exception t) {
  395.             throw new UtilsException("Serialization error (nome:"+p.getNome()+" classe:"+p.getClasse()+"): "+t.getMessage(), t);
  396.         }
  397.     }
  398. }