DynamicUtils.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.dynamic;

  21. import java.io.ByteArrayInputStream;
  22. import java.io.OutputStream;
  23. import java.io.OutputStreamWriter;
  24. import java.io.Writer;
  25. import java.util.ArrayList;
  26. import java.util.Enumeration;
  27. import java.util.HashMap;
  28. import java.util.Iterator;
  29. import java.util.List;
  30. import java.util.Map;

  31. import javax.servlet.http.HttpServletRequest;
  32. import javax.xml.transform.Source;
  33. import javax.xml.transform.Transformer;
  34. import javax.xml.transform.dom.DOMSource;
  35. import javax.xml.transform.stream.StreamResult;
  36. import javax.xml.transform.stream.StreamSource;

  37. import org.apache.commons.lang.StringUtils;
  38. import org.openspcoop2.core.id.IDServizioApplicativo;
  39. import org.openspcoop2.message.OpenSPCoop2Message;
  40. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  41. import org.openspcoop2.message.OpenSPCoop2RestJsonMessage;
  42. import org.openspcoop2.message.OpenSPCoop2RestXmlMessage;
  43. import org.openspcoop2.message.OpenSPCoop2SoapMessage;
  44. import org.openspcoop2.message.constants.MessageRole;
  45. import org.openspcoop2.message.constants.MessageType;
  46. import org.openspcoop2.message.constants.ServiceBinding;
  47. import org.openspcoop2.message.utils.DumpAttachment;
  48. import org.openspcoop2.message.utils.DumpMessaggio;
  49. import org.openspcoop2.message.xml.MessageXMLUtils;
  50. import org.openspcoop2.pdd.core.CostantiPdD;
  51. import org.openspcoop2.pdd.core.token.InformazioniToken;
  52. import org.openspcoop2.pdd.core.token.attribute_authority.InformazioniAttributi;
  53. import org.openspcoop2.pdd.services.connector.FormUrlEncodedHttpServletRequest;
  54. import org.openspcoop2.protocol.sdk.Busta;
  55. import org.openspcoop2.protocol.sdk.Context;
  56. import org.openspcoop2.protocol.sdk.SecurityToken;
  57. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  58. import org.openspcoop2.utils.DynamicStringReplace;
  59. import org.openspcoop2.utils.date.DateManager;
  60. import org.openspcoop2.utils.io.ArchiveType;
  61. import org.openspcoop2.utils.io.CompressorUtilities;
  62. import org.openspcoop2.utils.io.Entry;
  63. import org.openspcoop2.utils.resources.FreemarkerTemplateLoader;
  64. import org.openspcoop2.utils.resources.TemplateUtils;
  65. import org.openspcoop2.utils.resources.VelocityTemplateUtils;
  66. import org.openspcoop2.utils.transport.TransportUtils;
  67. import org.openspcoop2.utils.transport.http.HttpServletTransportRequestContext;
  68. import org.slf4j.Logger;
  69. import org.w3c.dom.Element;

  70. import freemarker.ext.beans.BeansWrapper;
  71. import freemarker.template.Configuration;
  72. import freemarker.template.TemplateModel;

  73. /**
  74.  * DynamicUtils
  75.  *
  76.  * @author Andrea Poli (apoli@link.it)
  77.  * @author $Author$
  78.  * @version $Rev$, $Date$
  79.  */
  80. public class DynamicUtils {
  81.    
  82.     private DynamicUtils() {}

  83.     // *** DYNAMIC MAP ***
  84.    
  85.     // NOTA: uso volutamente le stesse costanti del connettore File
  86.    
  87.     public static void fillDynamicMapRequest(Logger log, Map<String, Object> dynamicMap, Context pddContext, String urlInvocazione,
  88.             OpenSPCoop2Message message,
  89.             MessageContent messageContent,
  90.             Busta busta,
  91.             Map<String, List<String>> trasporto,
  92.             Map<String, List<String>> url,
  93.             Map<String, List<String>> form,
  94.             ErrorHandler errorHandler) {
  95.         fillDynamicMapEngine(log, dynamicMap, pddContext, urlInvocazione,
  96.                 message,
  97.                 messageContent,
  98.                 busta,
  99.                 trasporto,
  100.                 url,
  101.                 form,
  102.                 errorHandler);  
  103.     }
  104.     public static void fillDynamicMapResponse(Logger log, Map<String, Object> dynamicMap, Map<String, Object> dynamicMapRequest, Context pddContext,
  105.             OpenSPCoop2Message message,
  106.             MessageContent messageContent,
  107.             Busta busta, Map<String, List<String>> trasporto,
  108.             ErrorHandler errorHandler) {
  109.         fillDynamicMapResponse(log, dynamicMap, dynamicMapRequest, pddContext,
  110.                 message,
  111.                 messageContent,
  112.                 busta, trasporto,
  113.                 errorHandler,
  114.                 false);
  115.     }
  116.     public static void fillDynamicMapResponse(Logger log, Map<String, Object> dynamicMap, Map<String, Object> dynamicMapRequest, Context pddContext,
  117.             OpenSPCoop2Message message,
  118.             MessageContent messageContent,
  119.             Busta busta, Map<String, List<String>> trasporto,
  120.             ErrorHandler errorHandler,
  121.             boolean preserveRequest) {
  122.         Map<String, Object> dynamicMapResponse = new HashMap<>();
  123.         fillDynamicMapEngine(log, dynamicMapResponse, pddContext, null,
  124.                 message,
  125.                 messageContent,
  126.                 busta,
  127.                 trasporto,
  128.                 null,
  129.                 null,
  130.                 errorHandler);
  131.         if(!dynamicMapResponse.isEmpty()) {
  132.             Iterator<String> it = dynamicMapResponse.keySet().iterator();
  133.             while (it.hasNext()) {
  134.                 String key = it.next();
  135.                 Object o = dynamicMapResponse.get(key);
  136.                 if(Costanti.MAP_ERROR_HANDLER_OBJECT.equalsIgnoreCase(key)
  137.                         ||
  138.                     Costanti.MAP_RESPONSE.equalsIgnoreCase(key)
  139.                         ||
  140.                     Costanti.MAP_INTEGRATION.equalsIgnoreCase(key)
  141.                         ||
  142.                     (Costanti.MAP_INTEGRATION+Costanti.MAP_SUFFIX_RESPONSE).equalsIgnoreCase(key)
  143.                     ){
  144.                     dynamicMap.put(key, o);
  145.                 }
  146.                 else {
  147.                     String keyResponse = key+Costanti.MAP_SUFFIX_RESPONSE;
  148.                     dynamicMap.put(keyResponse, o);
  149.                     dynamicMap.put(keyResponse.toLowerCase(), o);
  150.                     if(Costanti.MAP_HEADER_VALUES.equals(key)) {
  151.                         // scritta piu' corretta, pero' lascio anche la precedente
  152.                         dynamicMap.put(Costanti.MAP_HEADER_RESPONSE_VALUES, o);
  153.                         dynamicMap.put(Costanti.MAP_HEADER_RESPONSE_VALUES.toLowerCase(), o);
  154.                     }
  155.                 }
  156.             }
  157.         }
  158.         if(dynamicMapRequest!=null && !dynamicMapRequest.isEmpty()) {
  159.             Iterator<String> it = dynamicMapRequest.keySet().iterator();
  160.             while (it.hasNext()) {
  161.                 String key = it.next();
  162.                 if(Costanti.MAP_ERROR_HANDLER_OBJECT.equalsIgnoreCase(key)
  163.                         ||
  164.                     (Costanti.MAP_REQUEST.equalsIgnoreCase(key) && !preserveRequest)
  165.                         ){
  166.                     continue; // error handler viene usato quello istanziato per la risposta; mentre la richiesta è già stata consumata.
  167.                 }
  168.                 Object o = dynamicMapRequest.get(key);
  169.                 if(o instanceof PatternExtractor) {
  170.                     PatternExtractor pe = (PatternExtractor) o;
  171.                     pe.refreshContent();
  172.                 }
  173.                 dynamicMap.put(key, o);
  174.             }
  175.         }
  176.     }
  177.     private static void fillDynamicMapEngine(Logger log, Map<String, Object> dynamicMap, Context pddContext, String urlInvocazione,
  178.             OpenSPCoop2Message message,
  179.             MessageContent messageContent,
  180.             Busta busta,
  181.             Map<String, List<String>> trasporto,
  182.             Map<String, List<String>> url,
  183.             Map<String, List<String>> form,
  184.             ErrorHandler errorHandler) {
  185.         DynamicInfo dInfo = new DynamicInfo();
  186.         dInfo.setBusta(busta);
  187.         dInfo.setPddContext(pddContext);
  188.         if(trasporto!=null) {
  189.             /** && !trasporto.isEmpty()) {
  190.             //Map<String, String> pNew = new HashMap<>();
  191.             //pNew.putAll(trasporto);
  192.             //dInfo.setTrasporto(pNew);
  193.             // Fix per permettere la modifica degli header direttamente dentro la trasformazione */
  194.             dInfo.setHeaders(trasporto);
  195.         }
  196.         if(url!=null) {
  197.             /** && !url.isEmpty()) {
  198.             //Map<String, String> pNew = new HashMap<>();
  199.             //pNew.putAll(url);
  200.             //dInfo.setQueryParameters(pNew);
  201.             // Fix per permettere la modifica dei parametri direttamente dentro la trasformazione */
  202.             dInfo.setParameters(url);
  203.         }
  204.         if(form!=null) {
  205.             /** && !url.isEmpty()) {
  206.             //Map<String, String> pNew = new HashMap<>();
  207.             //pNew.putAll(url);
  208.             //dInfo.setQueryParameters(pNew);
  209.             // Fix per permettere la modifica dei parametri direttamente dentro la trasformazione */
  210.             dInfo.setFormParameters(form);
  211.         }
  212.         if(urlInvocazione!=null) {
  213.             dInfo.setUrl(urlInvocazione);
  214.         }
  215.         if(messageContent!=null) {
  216.             dInfo.setMessageContent(messageContent);
  217.         }
  218.         if(message!=null) {
  219.             dInfo.setMessage(message);
  220.         }
  221.         dInfo.setErrorHandler(errorHandler);
  222.         DynamicUtils.fillDynamicMap(log, dynamicMap, dInfo);        
  223.     }
  224.    
  225.     public static void fillDynamicMap(Logger log, Map<String, Object> dynamicMap, DynamicInfo dynamicInfo) {
  226.         fillDynamicMap(log,dynamicMap, dynamicInfo, false);
  227.     }
  228.     @SuppressWarnings("unchecked")
  229.     public static void fillDynamicMap(Logger log, Map<String, Object> dynamicMap, DynamicInfo dynamicInfo, boolean initFromJmx) {
  230.         if(!dynamicMap.containsKey(Costanti.MAP_DATE_OBJECT)) {
  231.             dynamicMap.put(Costanti.MAP_DATE_OBJECT, DateManager.getDate());
  232.         }
  233.        
  234.         RequestInfo requestInfo = null;
  235.        
  236.         if(dynamicInfo!=null && dynamicInfo.getPddContext()!=null) {
  237.            
  238.             if(!dynamicMap.containsKey(Costanti.MAP_CTX_OBJECT)) {
  239.                 dynamicMap.put(Costanti.MAP_CTX_OBJECT, dynamicInfo.getPddContext());
  240.             }
  241.             if(!dynamicMap.containsKey(Costanti.MAP_SYNC_CTX_OBJECT) &&
  242.                     dynamicInfo.getPddContext().containsKey(CostantiPdD.CONTESTO_RICHIESTA_MESSAGGIO_NOTIFICA)) {
  243.                 Context transactionSyncContext = (Context)dynamicInfo.getPddContext().getObject(CostantiPdD.CONTESTO_RICHIESTA_MESSAGGIO_NOTIFICA);
  244.                 dynamicMap.put(Costanti.MAP_SYNC_CTX_OBJECT, transactionSyncContext);
  245.             }
  246.             if(!dynamicMap.containsKey(Costanti.MAP_TRANSACTION_ID_OBJECT) &&
  247.                 dynamicInfo.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) {
  248.                 String idTransazione = (String)dynamicInfo.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  249.                 dynamicMap.put(Costanti.MAP_TRANSACTION_ID_OBJECT, idTransazione);
  250.             }
  251.             if(dynamicInfo.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.REQUEST_INFO)) {
  252.                 requestInfo = (RequestInfo)dynamicInfo.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.REQUEST_INFO);
  253.             }
  254.             if(!dynamicMap.containsKey(Costanti.MAP_URL_PROTOCOL_CONTEXT_OBJECT) &&
  255.                 requestInfo!=null) {
  256.                 if(requestInfo.getProtocolContext()!=null) {
  257.                     dynamicMap.put(Costanti.MAP_URL_PROTOCOL_CONTEXT_OBJECT, requestInfo.getProtocolContext());
  258.                     dynamicMap.put(Costanti.MAP_URL_PROTOCOL_CONTEXT_OBJECT.toLowerCase(), requestInfo.getProtocolContext());
  259.                 }
  260.                 if(requestInfo.getIdServizio()!=null) {
  261.                     AttachmentsReader aReader = new AttachmentsReader(requestInfo.getIdServizio(), requestInfo);
  262.                     dynamicMap.put(Costanti.MAP_ATTACHMENTS_OBJECT, aReader);
  263.                 }
  264.             }
  265.             if(!dynamicMap.containsKey(Costanti.MAP_INTEGRATION)) {
  266.                 Object oInformazioniIntegrazione = dynamicInfo.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.INFORMAZIONI_INTEGRAZIONE);
  267.                 if(oInformazioniIntegrazione!=null) {
  268.                     InformazioniIntegrazione informazioniIntegrazione = (InformazioniIntegrazione) oInformazioniIntegrazione;
  269.                     dynamicMap.put(Costanti.MAP_INTEGRATION, informazioniIntegrazione);
  270.                 }
  271.             }
  272.             if(!dynamicMap.containsKey((Costanti.MAP_INTEGRATION+Costanti.MAP_SUFFIX_RESPONSE))) {
  273.                 Object oInformazioniIntegrazione = dynamicInfo.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.INFORMAZIONI_INTEGRAZIONE_RISPOSTA);
  274.                 if(oInformazioniIntegrazione!=null) {
  275.                     InformazioniIntegrazione informazioniIntegrazione = (InformazioniIntegrazione) oInformazioniIntegrazione;
  276.                     dynamicMap.put((Costanti.MAP_INTEGRATION+Costanti.MAP_SUFFIX_RESPONSE), informazioniIntegrazione);
  277.                     dynamicMap.put((Costanti.MAP_INTEGRATION+Costanti.MAP_SUFFIX_RESPONSE).toLowerCase(), informazioniIntegrazione);
  278.                 }
  279.             }
  280.             if(!dynamicMap.containsKey(Costanti.MAP_TOKEN_INFO)) {
  281.                 Object oInformazioniTokenNormalizzate = dynamicInfo.getPddContext().getObject(org.openspcoop2.pdd.core.token.Costanti.PDD_CONTEXT_TOKEN_INFORMAZIONI_NORMALIZZATE);
  282.                 if(oInformazioniTokenNormalizzate!=null) {
  283.                     InformazioniToken informazioniTokenNormalizzate = (InformazioniToken) oInformazioniTokenNormalizzate;
  284.                     dynamicMap.put(Costanti.MAP_TOKEN_INFO, informazioniTokenNormalizzate);
  285.                     dynamicMap.put(Costanti.MAP_TOKEN_INFO.toLowerCase(), informazioniTokenNormalizzate);
  286.                 }
  287.             }
  288.             if(!dynamicMap.containsKey(Costanti.MAP_ATTRIBUTES)) {
  289.                 Object oInformazioniAttributiNormalizzati = dynamicInfo.getPddContext().getObject(org.openspcoop2.pdd.core.token.Costanti.PDD_CONTEXT_ATTRIBUTI_INFORMAZIONI_NORMALIZZATE);
  290.                 if(oInformazioniAttributiNormalizzati!=null) {
  291.                     InformazioniAttributi informazioniAttributiNormalizzati = (InformazioniAttributi) oInformazioniAttributiNormalizzati;
  292.                     dynamicMap.put(Costanti.MAP_ATTRIBUTES, informazioniAttributiNormalizzati);
  293.                 }
  294.             }
  295.             if(!dynamicMap.containsKey(Costanti.MAP_SECURITY_TOKEN)) {
  296.                 Object oSecToken = dynamicInfo.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.SECURITY_TOKEN);
  297.                 if(oSecToken!=null) {
  298.                     SecurityToken securityToken = (SecurityToken) oSecToken;
  299.                     dynamicMap.put(Costanti.MAP_SECURITY_TOKEN, securityToken);
  300.                 }
  301.             }
  302.             if (!dynamicMap.containsKey(Costanti.MAP_API_IMPL_CONFIG_PROPERTY)) {
  303.                 Map<String, String> configProperties = null; // aggiungo sempre, piu' pratico il controllo nei template engine
  304.                 if (dynamicInfo.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.PROPRIETA_CONFIGURAZIONE)) {
  305.                     configProperties = (Map<String, String>)dynamicInfo.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_CONFIGURAZIONE);
  306.                 }
  307.                 if(configProperties==null) {
  308.                     configProperties = new HashMap<>();
  309.                 }
  310.                 dynamicMap.put(Costanti.MAP_API_IMPL_CONFIG_PROPERTY, configProperties);
  311.             }
  312.             if (!dynamicMap.containsKey(Costanti.MAP_APPLICATIVO_CONFIG_PROPERTY)) {
  313.                 Map<String, String> configProperties = null; // aggiungo sempre, piu' pratico il controllo nei template engine
  314.                 if (dynamicInfo.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.PROPRIETA_APPLICATIVO)) {
  315.                     configProperties = (Map<String, String>)dynamicInfo.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_APPLICATIVO);
  316.                 }
  317.                 if(configProperties==null) {
  318.                     configProperties = new HashMap<>();
  319.                 }
  320.                 dynamicMap.put(Costanti.MAP_APPLICATIVO_CONFIG_PROPERTY, configProperties);
  321.                 dynamicMap.put(Costanti.MAP_APPLICATIVO_CONFIG_PROPERTY.toLowerCase(), configProperties);
  322.             }
  323.             if (!dynamicMap.containsKey(Costanti.MAP_SOGGETTO_FRUITORE_CONFIG_PROPERTY)) {
  324.                 Map<String, String> configProperties = null; // aggiungo sempre, piu' pratico il controllo nei template engine
  325.                 if (dynamicInfo.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_FRUITORE)) {
  326.                     configProperties = (Map<String, String>)dynamicInfo.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_FRUITORE);
  327.                 }
  328.                 if(configProperties==null) {
  329.                     configProperties = new HashMap<>();
  330.                 }
  331.                 dynamicMap.put(Costanti.MAP_SOGGETTO_FRUITORE_CONFIG_PROPERTY, configProperties);
  332.                 dynamicMap.put(Costanti.MAP_SOGGETTO_FRUITORE_CONFIG_PROPERTY.toLowerCase(), configProperties);
  333.             }
  334.             if (!dynamicMap.containsKey(Costanti.MAP_SOGGETTO_EROGATORE_CONFIG_PROPERTY)) {
  335.                 Map<String, String> configProperties = null; // aggiungo sempre, piu' pratico il controllo nei template engine
  336.                 if (dynamicInfo.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_EROGATORE)) {
  337.                     configProperties = (Map<String, String>)dynamicInfo.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_EROGATORE);
  338.                 }
  339.                 if(configProperties==null) {
  340.                     configProperties = new HashMap<>();
  341.                 }
  342.                 dynamicMap.put(Costanti.MAP_SOGGETTO_EROGATORE_CONFIG_PROPERTY, configProperties);
  343.                 dynamicMap.put(Costanti.MAP_SOGGETTO_EROGATORE_CONFIG_PROPERTY.toLowerCase(), configProperties);
  344.             }
  345.             if (!dynamicMap.containsKey(Costanti.MAP_APPLICATIVO_TOKEN)) {
  346.                 IDServizioApplicativo idApplicativoToken = null;
  347.                 if (dynamicInfo.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.ID_APPLICATIVO_TOKEN)) {
  348.                     idApplicativoToken = (IDServizioApplicativo)dynamicInfo.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_APPLICATIVO_TOKEN);
  349.                 }
  350.                 if(idApplicativoToken!=null) {
  351.                     dynamicMap.put(Costanti.MAP_APPLICATIVO_TOKEN, idApplicativoToken);
  352.                     dynamicMap.put(Costanti.MAP_APPLICATIVO_TOKEN.toLowerCase(), idApplicativoToken);
  353.                 }
  354.             }
  355.             if (!dynamicMap.containsKey(Costanti.MAP_APPLICATIVO_TOKEN_CONFIG_PROPERTY)) {
  356.                 Map<String, String> configProperties = null; // aggiungo sempre, piu' pratico il controllo nei template engine
  357.                 if (dynamicInfo.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.PROPRIETA_APPLICATIVO_TOKEN)) {
  358.                     configProperties = (Map<String, String>)dynamicInfo.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_APPLICATIVO_TOKEN);
  359.                 }
  360.                 if(configProperties==null) {
  361.                     configProperties = new HashMap<>();
  362.                 }
  363.                 dynamicMap.put(Costanti.MAP_APPLICATIVO_TOKEN_CONFIG_PROPERTY, configProperties);
  364.                 dynamicMap.put(Costanti.MAP_APPLICATIVO_TOKEN_CONFIG_PROPERTY.toLowerCase(), configProperties);
  365.             }
  366.             if (!dynamicMap.containsKey(Costanti.MAP_SOGGETTO_PROPRIETARIO_APPLICATIVO_TOKEN_CONFIG_PROPERTY)) {
  367.                 Map<String, String> configProperties = null; // aggiungo sempre, piu' pratico il controllo nei template engine
  368.                 if (dynamicInfo.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_PROPRIETARIO_APPLICATIVO_TOKEN)) {
  369.                     configProperties = (Map<String, String>)dynamicInfo.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_PROPRIETARIO_APPLICATIVO_TOKEN);
  370.                 }
  371.                 if(configProperties==null) {
  372.                     configProperties = new HashMap<>();
  373.                 }
  374.                 dynamicMap.put(Costanti.MAP_SOGGETTO_PROPRIETARIO_APPLICATIVO_TOKEN_CONFIG_PROPERTY, configProperties);
  375.                 dynamicMap.put(Costanti.MAP_SOGGETTO_PROPRIETARIO_APPLICATIVO_TOKEN_CONFIG_PROPERTY.toLowerCase(), configProperties);
  376.             }
  377.         }
  378.        
  379.         if(!dynamicMap.containsKey(Costanti.MAP_BUSTA_OBJECT) && dynamicInfo!=null && dynamicInfo.getBusta()!=null) {
  380.             dynamicMap.put(Costanti.MAP_BUSTA_OBJECT, dynamicInfo.getBusta());
  381.         }
  382.         if(!dynamicMap.containsKey(Costanti.MAP_BUSTA_PROPERTY) && dynamicInfo!=null &&
  383.                 dynamicInfo.getBusta()!=null && dynamicInfo.getBusta().sizeProperties()>0) {
  384.             Map<String, String> propertiesBusta = new HashMap<>();
  385.             String[] pNames = dynamicInfo.getBusta().getPropertiesNames();
  386.             if(pNames!=null && pNames.length>0) {
  387.                 for (int j = 0; j < pNames.length; j++) {
  388.                     String pName = pNames[j];
  389.                     String pValue = dynamicInfo.getBusta().getProperty(pName);
  390.                     if(pValue!=null) {
  391.                         propertiesBusta.put(pName, pValue);
  392.                     }
  393.                 }
  394.             }
  395.             if(!propertiesBusta.isEmpty()) {
  396.                 dynamicMap.put(Costanti.MAP_BUSTA_PROPERTY, propertiesBusta);
  397.             }
  398.         }
  399.        
  400.         if(!dynamicMap.containsKey(Costanti.MAP_HEADER)) {
  401.             if(dynamicInfo!=null && dynamicInfo.getHeaders()!=null && !dynamicInfo.getHeaders().isEmpty()) {
  402.                 dynamicMap.put(Costanti.MAP_HEADER, TransportUtils.convertToMapSingleValue(dynamicInfo.getHeaders()));
  403.             }
  404.             else {
  405.                 dynamicMap.put(Costanti.MAP_HEADER, new HashMap<>()); // aggiungo sempre, piu' pratico il controllo nei template engine
  406.             }
  407.         }
  408.        
  409.         if(!dynamicMap.containsKey(Costanti.MAP_HEADER_VALUES)) {
  410.             if(dynamicInfo!=null && dynamicInfo.getHeaders()!=null) {
  411.                 dynamicMap.put(Costanti.MAP_HEADER_VALUES, dynamicInfo.getHeaders());
  412.             }
  413.             else {
  414.                 dynamicMap.put(Costanti.MAP_HEADER_VALUES, new HashMap<>()); // aggiungo sempre, piu' pratico il controllo nei template engine
  415.             }
  416.         }
  417.        
  418.         if(!dynamicMap.containsKey(Costanti.MAP_QUERY_PARAMETER)) {
  419.             if(dynamicInfo!=null && dynamicInfo.getParameters()!=null && !dynamicInfo.getParameters().isEmpty()) {
  420.                 dynamicMap.put(Costanti.MAP_QUERY_PARAMETER, TransportUtils.convertToMapSingleValue(dynamicInfo.getParameters()));
  421.             }
  422.             else {
  423.                 dynamicMap.put(Costanti.MAP_QUERY_PARAMETER, new HashMap<>()); // aggiungo sempre, piu' pratico il controllo nei template engine
  424.             }
  425.         }
  426.        
  427.         if(!dynamicMap.containsKey(Costanti.MAP_QUERY_PARAMETER_VALUES)) {
  428.             if(dynamicInfo!=null && dynamicInfo.getParameters()!=null) {
  429.                 dynamicMap.put(Costanti.MAP_QUERY_PARAMETER_VALUES, dynamicInfo.getParameters());
  430.             }
  431.             else {
  432.                 dynamicMap.put(Costanti.MAP_QUERY_PARAMETER_VALUES, new HashMap<>()); // aggiungo sempre, piu' pratico il controllo nei template engine
  433.             }
  434.         }
  435.        
  436.         if(!dynamicMap.containsKey(Costanti.MAP_FORM_PARAMETER)) {
  437.             if(dynamicInfo!=null && dynamicInfo.getFormParameters()!=null && !dynamicInfo.getFormParameters().isEmpty()) {
  438.                 dynamicMap.put(Costanti.MAP_FORM_PARAMETER, TransportUtils.convertToMapSingleValue(dynamicInfo.getFormParameters()));
  439.             }
  440.             else {
  441.                 dynamicMap.put(Costanti.MAP_FORM_PARAMETER, new HashMap<>()); // aggiungo sempre, piu' pratico il controllo nei template engine
  442.             }
  443.         }
  444.        
  445.         if(!dynamicMap.containsKey(Costanti.MAP_FORM_PARAMETER_VALUES)) {
  446.             if(dynamicInfo!=null && dynamicInfo.getFormParameters()!=null) {
  447.                 dynamicMap.put(Costanti.MAP_FORM_PARAMETER_VALUES, dynamicInfo.getFormParameters());
  448.             }
  449.             else {
  450.                 dynamicMap.put(Costanti.MAP_FORM_PARAMETER_VALUES, new HashMap<>()); // aggiungo sempre, piu' pratico il controllo nei template engine
  451.             }
  452.         }
  453.        
  454.         try {
  455.             SystemPropertiesReader systemPropertiesReader = new SystemPropertiesReader(log, requestInfo, initFromJmx);
  456.             dynamicMap.put(Costanti.MAP_SYSTEM_PROPERTY, systemPropertiesReader);
  457.             dynamicMap.put(Costanti.MAP_SYSTEM_PROPERTY.toLowerCase(), systemPropertiesReader);
  458.         }
  459.         catch(Exception e) {
  460.             log.error("Creazione system properties reader fallita: "+e.getMessage(),e);
  461.         }
  462.        
  463.         EnvironmentPropertiesReader environmentPropertiesReader = new EnvironmentPropertiesReader(log);
  464.         dynamicMap.put(Costanti.MAP_ENV_PROPERTY, environmentPropertiesReader);
  465.         dynamicMap.put(Costanti.MAP_ENV_PROPERTY.toLowerCase(), environmentPropertiesReader);
  466.        
  467.         JavaPropertiesReader javaPropertiesReader = new JavaPropertiesReader(log);
  468.         dynamicMap.put(Costanti.MAP_JAVA_PROPERTY, javaPropertiesReader);
  469.         dynamicMap.put(Costanti.MAP_JAVA_PROPERTY.toLowerCase(), javaPropertiesReader);
  470.        
  471.         EnvironmentJavaPropertiesReader envJavaPropertiesReader = new EnvironmentJavaPropertiesReader(log);
  472.         dynamicMap.put(Costanti.MAP_ENV_JAVA_PROPERTY, envJavaPropertiesReader);
  473.         dynamicMap.put(Costanti.MAP_ENV_JAVA_PROPERTY.toLowerCase(), envJavaPropertiesReader);
  474.        
  475.         // questi sottostanti, non sono disponnibili sul connettore
  476.         if(dynamicInfo!=null && dynamicInfo.getUrl()!=null) {
  477.             URLRegExpExtractor urle = new URLRegExpExtractor(dynamicInfo.getUrl(), log);
  478.             dynamicMap.put(Costanti.MAP_ELEMENT_URL_REGEXP, urle);
  479.             dynamicMap.put(Costanti.MAP_ELEMENT_URL_REGEXP.toLowerCase(), urle);
  480.         }
  481.         if(dynamicInfo!=null && dynamicInfo.getMessageContent()!=null &&
  482.                 (dynamicInfo.getMessageContent().isXml() || dynamicInfo.getMessageContent().isRestMultipart())) {
  483.             OpenSPCoop2MessageFactory messageFactory = dynamicInfo.getMessage()!=null ? dynamicInfo.getMessage().getFactory() : OpenSPCoop2MessageFactory.getDefaultMessageFactory();
  484.             PatternExtractor pe = new PatternExtractor(messageFactory, dynamicInfo.getMessageContent(), log);
  485.             dynamicMap.put(Costanti.MAP_ELEMENT_XML_XPATH, pe);
  486.             dynamicMap.put(Costanti.MAP_ELEMENT_XML_XPATH.toLowerCase(), pe);
  487.         }
  488.         if(dynamicInfo!=null && dynamicInfo.getMessageContent()!=null &&
  489.                 (dynamicInfo.getMessageContent().isJson() || dynamicInfo.getMessageContent().isRestMultipart())) {
  490.             OpenSPCoop2MessageFactory messageFactory = dynamicInfo.getMessage()!=null ? dynamicInfo.getMessage().getFactory() : OpenSPCoop2MessageFactory.getDefaultMessageFactory();
  491.             PatternExtractor pe = new PatternExtractor(messageFactory, dynamicInfo.getMessageContent(), log);
  492.             dynamicMap.put(Costanti.MAP_ELEMENT_JSON_PATH, pe);
  493.             dynamicMap.put(Costanti.MAP_ELEMENT_JSON_PATH.toLowerCase(), pe);
  494.         }
  495.         if(dynamicInfo!=null && dynamicInfo.getMessage()!=null) {
  496.             ContentExtractor content = new ContentExtractor(dynamicInfo.getMessage(), dynamicInfo.getPddContext(), log);
  497.             if(MessageRole.REQUEST.equals(dynamicInfo.getMessage().getMessageRole())) {
  498.                 dynamicMap.put(Costanti.MAP_REQUEST, content);
  499.             }
  500.             else {
  501.                 dynamicMap.put(Costanti.MAP_RESPONSE, content);
  502.             }
  503.         }
  504.         if(dynamicInfo!=null && dynamicInfo.getErrorHandler()!=null) {
  505.             dynamicMap.put(Costanti.MAP_ERROR_HANDLER_OBJECT, dynamicInfo.getErrorHandler());
  506.             dynamicMap.put(Costanti.MAP_ERROR_HANDLER_OBJECT.toLowerCase(), dynamicInfo.getErrorHandler());
  507.         }
  508.        
  509.         if(!dynamicMap.containsKey(Costanti.MAP_DYNAMIC_CONFIG_PROPERTY)) {
  510.             dynamicMap.put(Costanti.MAP_DYNAMIC_CONFIG_PROPERTY, new DynamicConfig(log, dynamicMap, requestInfo,
  511.                     dynamicInfo!=null ? dynamicInfo.getBusta() : null));
  512.         }
  513.        
  514.     }
  515.    
  516.    
  517.    
  518.     // DYNAMIC MAP
  519.    
  520.     // Mappa che non contiene 'response' field
  521.     @Deprecated
  522.     // Cercare sempre di passare l'oggetto busta
  523.     public static Map<String, Object> buildDynamicMap(OpenSPCoop2Message msg, Context context, Logger log,
  524.             boolean bufferMessageReadOnly) throws DynamicException {
  525.         return buildDynamicMap(msg, context, null, log,
  526.                 bufferMessageReadOnly);
  527.     }
  528.     public static Map<String, Object> buildDynamicMap(OpenSPCoop2Message msg, Context context, Busta busta, Logger log,
  529.             boolean bufferMessageReadOnly) throws DynamicException {
  530.         return buildDynamicMapEngine(msg, context, busta, log,
  531.                 bufferMessageReadOnly,
  532.                 null);
  533.     }
  534.    
  535.     // Mappa che contiene 'response' field
  536.     public static Map<String, Object> buildDynamicMapResponse(OpenSPCoop2Message msg, Context context, Busta busta, Logger log,
  537.             boolean bufferMessageReadOnly,
  538.             Map<String, Object>  dynamicMapRequest) throws DynamicException {
  539.         return buildDynamicMapEngine(msg, context, busta, log,
  540.                 bufferMessageReadOnly,
  541.                 dynamicMapRequest);
  542.     }
  543.    
  544.     private static Map<String, Object> buildDynamicMapEngine(OpenSPCoop2Message msg, Context context, Busta busta, Logger log,
  545.             boolean bufferMessageReadOnly,
  546.             Map<String, Object>  dynamicMapRequest) throws DynamicException {
  547.        
  548.         /* Costruisco dynamic Map */
  549.        
  550.         DynamicInfo dInfo = DynamicUtils.readDynamicInfo(msg,
  551.                 bufferMessageReadOnly, context);
  552.         MessageContent messageContent = dInfo.getMessageContent();
  553.         Map<String, List<String>> parametriTrasporto = dInfo.getHeaders();
  554.         Map<String, List<String>> parametriUrl = dInfo.getParameters();
  555.         Map<String, List<String>> parametriForm = dInfo.getFormParameters();
  556.         String urlInvocazione = dInfo.getUrl();
  557.         Map<String, Object> dynamicMap = new HashMap<>();
  558.         ErrorHandler errorHandler = new ErrorHandler();
  559.        
  560.         if(dynamicMapRequest!=null) {
  561.             fillDynamicMapResponse(log, dynamicMap, dynamicMapRequest, context,
  562.                     msg,
  563.                     messageContent,
  564.                     busta,
  565.                     parametriTrasporto,
  566.                     errorHandler);
  567.             return dynamicMap;
  568.         }
  569.    
  570.         DynamicUtils.fillDynamicMapRequest(log, dynamicMap, context, urlInvocazione,
  571.                 msg,
  572.                 messageContent,
  573.                 busta,
  574.                 parametriTrasporto,
  575.                 parametriUrl,
  576.                 parametriForm,
  577.                 errorHandler);
  578.         return dynamicMap;

  579.     }
  580.    
  581.    
  582.    
  583.    
  584.    
  585.    
  586.     // READ DYNAMIC INFO
  587.    
  588.     public static DynamicInfo readDynamicInfo(OpenSPCoop2Message message, boolean bufferMessageReadOnly, Context context) throws DynamicException {
  589.         MessageContent content = null;
  590.         Map<String, List<String>> parametriTrasporto = null;
  591.         Map<String, List<String>> parametriUrl = null;
  592.         Map<String, List<String>> parametriForm = null;
  593.         String urlInvocazione = null;
  594.        
  595.         try{
  596.             if(ServiceBinding.SOAP.equals(message.getServiceBinding())){
  597.                 OpenSPCoop2SoapMessage soapMessage = message.castAsSoap();
  598.                 content = new MessageContent(soapMessage, bufferMessageReadOnly, context);
  599.             }
  600.             else{
  601.                 if(MessageType.XML.equals(message.getMessageType()) && message.castAsRest().hasContent()){
  602.                     OpenSPCoop2RestXmlMessage xml = message.castAsRestXml();
  603.                     content = new MessageContent(xml, bufferMessageReadOnly, context);
  604.                 }
  605.                 else if(MessageType.JSON.equals(message.getMessageType()) && message.castAsRest().hasContent()){
  606.                     OpenSPCoop2RestJsonMessage json = message.castAsRestJson();
  607.                     content = new MessageContent(json, bufferMessageReadOnly, context);
  608.                 }
  609.             }
  610.            

  611.             if(message.getTransportRequestContext()!=null) {
  612.                 if(message.getTransportRequestContext().getHeaders()!=null &&
  613.                     !message.getTransportRequestContext().getHeaders().isEmpty()) {
  614.                     parametriTrasporto = message.getTransportRequestContext().getHeaders();
  615.                 }
  616.                 if(message.getTransportRequestContext().getParameters()!=null &&
  617.                         !message.getTransportRequestContext().getParameters().isEmpty()) {
  618.                     parametriUrl = message.getTransportRequestContext().getParameters();
  619.                 }
  620.                 if(message.getTransportRequestContext() instanceof HttpServletTransportRequestContext) {
  621.                     HttpServletTransportRequestContext httpServletContext = (HttpServletTransportRequestContext) message.getTransportRequestContext();
  622.                     HttpServletRequest httpServletRequest = httpServletContext.getHttpServletRequest();
  623.                     if(httpServletRequest instanceof FormUrlEncodedHttpServletRequest) {
  624.                         FormUrlEncodedHttpServletRequest formServlet = (FormUrlEncodedHttpServletRequest) httpServletRequest;
  625.                         if(formServlet.getFormUrlEncodedParametersValues()!=null &&
  626.                                 !formServlet.getFormUrlEncodedParametersValues().isEmpty()) {
  627.                             parametriForm = formServlet.getFormUrlEncodedParametersValues();
  628.                         }
  629.                     }
  630.                 }
  631.                 urlInvocazione = message.getTransportRequestContext().getUrlInvocazione_formBased();
  632.             }
  633.             //else
  634.             // se c'e' la risposta devo usare quello come parametri della risposta
  635.                 if(message.getTransportResponseContext()!=null &&
  636.                         message.getTransportResponseContext().getHeaders()!=null &&
  637.                         !message.getTransportResponseContext().getHeaders().isEmpty()) {
  638.                     parametriTrasporto = message.getTransportResponseContext().getHeaders();
  639.             }
  640.            
  641.         }catch(Exception e){
  642.             throw new DynamicException(e.getMessage(),e);
  643.         }
  644.        
  645.         DynamicInfo dInfo = new DynamicInfo();
  646.         dInfo.setMessage(message);
  647.         dInfo.setMessageContent(content);
  648.         dInfo.setHeaders(parametriTrasporto);
  649.         dInfo.setParameters(parametriUrl);
  650.         dInfo.setFormParameters(parametriForm);
  651.         dInfo.setUrl(urlInvocazione);
  652.         return dInfo;
  653.     }
  654.    
  655.    
  656.    
  657.    
  658.     // *** TEMPLATE GOVWAY ***
  659.    
  660.     private static String initTemplateValue(String tmpParam, boolean forceStartWithDollaro,Context pddContext) {
  661.         String tmp = tmpParam;
  662.         if(!forceStartWithDollaro) {
  663.             // per retrocompatibilità nel connettore file gestisco entrambi
  664.             while(tmp.contains("${")) {
  665.                 tmp = tmp.replace("${", "{");
  666.             }
  667.         }
  668.        
  669.         String transactionIdConstant = Costanti.MAP_TRANSACTION_ID;
  670.         if(forceStartWithDollaro) {
  671.             transactionIdConstant = "$"+transactionIdConstant;
  672.         }
  673.         if(tmp.contains(transactionIdConstant)){
  674.             String idTransazione = (String)pddContext.getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  675.             while(tmp.contains(transactionIdConstant)){
  676.                 tmp = tmp.replace(transactionIdConstant, idTransazione);
  677.             }
  678.         }
  679.        
  680.         if(forceStartWithDollaro) {
  681.             transactionIdConstant = Costanti.MAP_TRANSACTION_ID;
  682.             transactionIdConstant = "?"+transactionIdConstant;
  683.             if(tmp.contains(transactionIdConstant)){
  684.                 String idTransazione = (String)pddContext.getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  685.                 while(tmp.contains(transactionIdConstant)){
  686.                     tmp = tmp.replace(transactionIdConstant, idTransazione);
  687.                 }
  688.             }
  689.         }
  690.                
  691.         return tmp;
  692.     }
  693.    
  694.     public static void validate(String name,String tmpParam, boolean addPrefixError) throws DynamicException{
  695.         validate(name, tmpParam, true, addPrefixError);
  696.     }
  697.     public static void validate(String name,String tmpParam, boolean forceStartWithDollaro, boolean addPrefixError) throws DynamicException{
  698.         Context pddContext = new Context();
  699.         pddContext.addObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, "fakeId");
  700.         String tmp = initTemplateValue(tmpParam, forceStartWithDollaro, pddContext);
  701.        
  702.         boolean onlyValidate = true;
  703.         tmp = processTemplateValueUrlXpathJsonpath(tmp, onlyValidate, null, forceStartWithDollaro);
  704.        
  705.         try{
  706.             DynamicStringReplace.validate(tmp, forceStartWithDollaro);
  707.         }catch(Exception e){
  708.             String prefix = addPrefixError ? "Proprieta' '"+name+"' contiene un valore non corretto: " : "";
  709.             throw new DynamicException(prefix+e.getMessage(),e);
  710.         }
  711.     }
  712.    
  713.     public static String convertDynamicPropertyValue(String name,String tmpParam,Map<String,Object> dynamicMap,Context pddContext) throws DynamicException{
  714.         return convertDynamicPropertyValue(name, tmpParam, dynamicMap, pddContext, true);
  715.     }
  716.     public static String convertDynamicPropertyValue(String name,String tmpParam,Map<String,Object> dynamicMap,Context pddContext, boolean forceStartWithDollaro) throws DynamicException{

  717.         String tmp = initTemplateValue(tmpParam, forceStartWithDollaro, pddContext);
  718.                
  719.         boolean onlyValidate = false;
  720.         tmp = processTemplateValueUrlXpathJsonpath(tmp, onlyValidate, dynamicMap, forceStartWithDollaro);
  721.        
  722.         try{
  723.             tmp = DynamicStringReplace.replace(tmp, dynamicMap, forceStartWithDollaro);
  724.         }catch(Exception e){
  725.             throw new DynamicException("Proprieta' '"+name+"' contiene un valore non corretto: "+e.getMessage(),e);
  726.         }
  727.         return tmp;
  728.     }
  729.    
  730.     private static String processTemplateValueUrlXpathJsonpath(String tmpParam, boolean onlyValidate, Map<String,Object> dynamicMap,
  731.             boolean forceStartWithDollaro) throws DynamicException {
  732.        
  733.         String tmp = tmpParam;
  734.         boolean request = false;
  735.         boolean response = true;
  736.        
  737.         // conversione url
  738.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  739.                 TemplateType.URL,
  740.                 forceStartWithDollaro, request,
  741.                 onlyValidate);
  742.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  743.                 TemplateType.URL,
  744.                 forceStartWithDollaro, response,
  745.                 onlyValidate);
  746.        
  747.         // conversione xpath
  748.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  749.                 TemplateType.XML,
  750.                 forceStartWithDollaro, request,
  751.                 onlyValidate);
  752.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  753.                 TemplateType.XML,
  754.                 forceStartWithDollaro, response,
  755.                 onlyValidate);
  756.        
  757.         // conversione jsonpath
  758.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  759.                 TemplateType.JSON,
  760.                 forceStartWithDollaro, request,
  761.                 onlyValidate);
  762.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  763.                 TemplateType.JSON,
  764.                 forceStartWithDollaro, response,
  765.                 onlyValidate);
  766.        
  767.         // conversione system properties
  768.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  769.                 TemplateType.SYSTEM,
  770.                 forceStartWithDollaro, request,
  771.                 onlyValidate);
  772.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  773.                 TemplateType.SYSTEM,
  774.                 forceStartWithDollaro, response,
  775.                 onlyValidate);
  776.        
  777.         // conversione env properties
  778.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  779.                 TemplateType.ENV,
  780.                 forceStartWithDollaro, request,
  781.                 onlyValidate);
  782.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  783.                 TemplateType.ENV,
  784.                 forceStartWithDollaro, response,
  785.                 onlyValidate);
  786.        
  787.         // conversione java properties
  788.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  789.                 TemplateType.JAVA,
  790.                 forceStartWithDollaro, request,
  791.                 onlyValidate);
  792.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  793.                 TemplateType.JAVA,
  794.                 forceStartWithDollaro, response,
  795.                 onlyValidate);
  796.        
  797.         // conversione env_java properties
  798.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  799.                 TemplateType.ENV_JAVA,
  800.                 forceStartWithDollaro, request,
  801.                 onlyValidate);
  802.         tmp = convertDynamicPropertyContent(tmp, dynamicMap,
  803.                 TemplateType.ENV_JAVA,
  804.                 forceStartWithDollaro, response,
  805.                 onlyValidate);
  806.        
  807.         return tmp;
  808.     }
  809.    
  810.     private static String convertDynamicPropertyContent(String tmpOriginal, Map<String,Object> dynamicMap,
  811.             TemplateType templateType,
  812.             boolean forceStartWithDollaro, boolean response,
  813.             boolean onlyValidate) throws DynamicException {
  814.        
  815.         if(tmpOriginal==null) {
  816.             return null; // precedente replace ha causato un null tramite opzione ?
  817.         }
  818.        
  819.         String istruzione = null;
  820.         String prefix = null;
  821.         switch (templateType) {
  822.         case XML:
  823.             istruzione = Costanti.MAP_ELEMENT_XML_XPATH;
  824.             prefix = Costanti.MAP_ELEMENT_XML_XPATH_PREFIX;
  825.             break;
  826.         case JSON:
  827.             istruzione = Costanti.MAP_ELEMENT_JSON_PATH;
  828.             prefix = Costanti.MAP_ELEMENT_JSON_PATH_PREFIX;
  829.             break;
  830.         case URL:
  831.             istruzione = Costanti.MAP_ELEMENT_URL_REGEXP;
  832.             prefix = Costanti.MAP_ELEMENT_URL_REGEXP_PREFIX;
  833.             break;
  834.         case SYSTEM:
  835.             istruzione = Costanti.MAP_SYSTEM_PROPERTY;
  836.             prefix = Costanti.MAP_SYSTEM_PROPERTY_PREFIX;
  837.             break;
  838.         case ENV:
  839.             istruzione = Costanti.MAP_ENV_PROPERTY;
  840.             prefix = Costanti.MAP_ENV_PROPERTY_PREFIX;
  841.             break;
  842.         case JAVA:
  843.             istruzione = Costanti.MAP_JAVA_PROPERTY;
  844.             prefix = Costanti.MAP_JAVA_PROPERTY_PREFIX;
  845.             break;
  846.         case ENV_JAVA:
  847.             istruzione = Costanti.MAP_ENV_JAVA_PROPERTY;
  848.             prefix = Costanti.MAP_ENV_JAVA_PROPERTY_PREFIX;
  849.             break;
  850.         }
  851.        

  852.         String tmp = tmpOriginal;
  853.         if(forceStartWithDollaro) {
  854.             String prefixDollaro = "$"+prefix;
  855.             tmp = convertDynamicPropertyContentEngine(tmp, dynamicMap,
  856.                     templateType,
  857.                     response,
  858.                     onlyValidate,
  859.                     istruzione, prefixDollaro);
  860.            
  861.             String prefixOptional = "?"+prefix;
  862.             tmp = convertDynamicPropertyContentEngine(tmp, dynamicMap,
  863.                     templateType,
  864.                     response,
  865.                     onlyValidate,
  866.                     istruzione, prefixOptional);
  867.         }
  868.         else {
  869.             tmp = convertDynamicPropertyContentEngine(tmp, dynamicMap,
  870.                     templateType,
  871.                     response,
  872.                     onlyValidate,
  873.                     istruzione, prefix);
  874.         }

  875.         if(tmpOriginal.trim().startsWith("?{") && tmp!=null && StringUtils.isEmpty(tmp)) {
  876.             return null;
  877.         }
  878.        
  879.         return tmp;
  880.     }
  881.     private static String convertDynamicPropertyContentEngine(String tmp, Map<String,Object> dynamicMap,
  882.             TemplateType templateType,
  883.             boolean response,
  884.             boolean onlyValidate,
  885.             String istruzione, String prefix) throws DynamicException {
  886.         if(response) {
  887.             istruzione = istruzione+Costanti.MAP_SUFFIX_RESPONSE;
  888.             prefix = prefix.substring(0,prefix.length()-1);
  889.             prefix = prefix + Costanti.MAP_SUFFIX_RESPONSE + ":";
  890.         }
  891.        
  892.         String tmpLowerCase = tmp.toLowerCase();
  893.         String prefixLowerCase = prefix.toLowerCase();
  894.        
  895.         if(tmpLowerCase.contains(prefixLowerCase)){
  896.             int maxIteration = 100;
  897.             while (maxIteration>0 && tmpLowerCase.contains(prefixLowerCase)) {
  898.                 int indexOfStart = tmpLowerCase.indexOf(prefixLowerCase);
  899.                 String pattern = tmp.substring(indexOfStart+prefix.length(),tmp.length());
  900.                 if(!pattern.contains("}")) {
  901.                     throw new DynamicException(buildPrefixIstruzioneMsgError(istruzione)+"non correttamente formata (chiusura '}' non trovata)");
  902.                 }
  903.                
  904.                 // cerco chiusura, all'interno ci potrebbero essere altre aperture di { per le regole xpath
  905.                 char [] patternChars = pattern.toCharArray();
  906.                 int numAperture = 0;
  907.                 int positionChiusura = -1;
  908.                 for (int i = 0; i < patternChars.length; i++) {
  909.                     if(patternChars[i] == '{') {
  910.                         numAperture++;
  911.                     }
  912.                     if(patternChars[i] == '}') {
  913.                         if(numAperture==0) {
  914.                             positionChiusura = i;
  915.                             break;
  916.                         }
  917.                         else {
  918.                             numAperture--;
  919.                         }
  920.                     }
  921.                 }
  922.                 if(positionChiusura<=0) {
  923.                     throw new DynamicException(buildPrefixIstruzioneMsgError(istruzione)+"non correttamente formata (chiusura '}' non trovata)");
  924.                 }
  925.                
  926.                 pattern = pattern.substring(0,positionChiusura);
  927.                
  928.                 String complete = tmp.substring(indexOfStart, positionChiusura+indexOfStart+prefix.length()+1);
  929.                 String value = getValue(dynamicMap,
  930.                         templateType,
  931.                         onlyValidate,
  932.                         istruzione,
  933.                         pattern);
  934.                 tmp = tmp.replace(complete, value);
  935.                 tmpLowerCase = tmp.toLowerCase();
  936.                 maxIteration--;
  937.             }
  938.         }
  939.        
  940.         return tmp;
  941.     }
  942.    
  943.     private static String getValue(Map<String,Object> dynamicMap,
  944.             TemplateType templateType,
  945.             boolean onlyValidate,
  946.             String istruzione,
  947.             String pattern) throws DynamicException {
  948.         String value = null;
  949.         if(!onlyValidate) {
  950.             Object o = dynamicMap.get(istruzione);
  951.             if(o==null) {
  952.                 throw new DynamicException(buildPrefixIstruzioneMsgError(istruzione)+"non utilizzabile in questo contesto");
  953.             }
  954.             switch (templateType) {
  955.             case XML:
  956.             case JSON:
  957.                 if( !(o instanceof PatternExtractor) ) {
  958.                     throw new DynamicException(buildPrefixIstruzioneMsgError(istruzione)+NON_UTILIZZABILE_IN_QUESTO_CONTESTO+buildExtractorWrongClassMsg(o));
  959.                 }
  960.                 PatternExtractor patternExtractor = (PatternExtractor) o;
  961.                 value = patternExtractor.read(pattern);
  962.                 break;
  963.             case URL:
  964.                 if( !(o instanceof URLRegExpExtractor) ) {
  965.                     throw new DynamicException(buildPrefixIstruzioneMsgError(istruzione)+NON_UTILIZZABILE_IN_QUESTO_CONTESTO+buildExtractorWrongClassMsg(o));
  966.                 }
  967.                 URLRegExpExtractor urlExtractor = (URLRegExpExtractor) o;
  968.                 value = urlExtractor.read(pattern);
  969.                 break;
  970.             case SYSTEM:
  971.                 value = getSystemProperty(o, istruzione, pattern);
  972.                 break;
  973.             case ENV:
  974.                 value = getEnvProperty(o, istruzione, pattern);
  975.                 break;
  976.             case JAVA:
  977.                 value = getJavaProperty(o, istruzione, pattern);
  978.                 break;
  979.             case ENV_JAVA:
  980.                 value = getEnvJavaProperty(o, istruzione, pattern);
  981.                 break;
  982.             }
  983.         }
  984.         if(value==null) {
  985.             value = "";
  986.         }
  987.         return value;
  988.     }
  989.     private static String getSystemProperty(Object o, String istruzione, String pattern) throws DynamicException {
  990.         if( !(o instanceof SystemPropertiesReader) ) {
  991.             throw new DynamicException(buildPrefixIstruzioneMsgError(istruzione)+NON_UTILIZZABILE_IN_QUESTO_CONTESTO+buildReaderWrongClassMsg(o));
  992.         }
  993.         SystemPropertiesReader systemPropertiesReader = (SystemPropertiesReader) o;
  994.         return systemPropertiesReader.read(pattern);
  995.     }
  996.     private static String getEnvProperty(Object o, String istruzione, String pattern) throws DynamicException {
  997.         if( !(o instanceof EnvironmentPropertiesReader) ) {
  998.             throw new DynamicException(buildPrefixIstruzioneMsgError(istruzione)+NON_UTILIZZABILE_IN_QUESTO_CONTESTO+buildReaderWrongClassMsg(o));
  999.         }
  1000.         EnvironmentPropertiesReader environmentPropertiesReader = (EnvironmentPropertiesReader) o;
  1001.         return environmentPropertiesReader.read(pattern);
  1002.     }
  1003.     private static String getJavaProperty(Object o, String istruzione, String pattern) throws DynamicException {
  1004.         if( !(o instanceof JavaPropertiesReader) ) {
  1005.             throw new DynamicException(buildPrefixIstruzioneMsgError(istruzione)+NON_UTILIZZABILE_IN_QUESTO_CONTESTO+buildReaderWrongClassMsg(o));
  1006.         }
  1007.         JavaPropertiesReader javaPropertiesReader = (JavaPropertiesReader) o;
  1008.         return javaPropertiesReader.read(pattern);
  1009.     }
  1010.     private static String getEnvJavaProperty(Object o, String istruzione, String pattern) throws DynamicException {
  1011.         if( !(o instanceof EnvironmentJavaPropertiesReader) ) {
  1012.             throw new DynamicException(buildPrefixIstruzioneMsgError(istruzione)+NON_UTILIZZABILE_IN_QUESTO_CONTESTO+buildReaderWrongClassMsg(o));
  1013.         }
  1014.         EnvironmentJavaPropertiesReader envJavaPropertiesReader = (EnvironmentJavaPropertiesReader) o;
  1015.         return envJavaPropertiesReader.read(pattern);
  1016.     }
  1017.     private static String buildPrefixIstruzioneMsgError(String istruzione) {
  1018.         return "Trovata istruzione '"+istruzione+"' ";
  1019.     }
  1020.     private static final String NON_UTILIZZABILE_IN_QUESTO_CONTESTO = "non utilizzabile in questo contesto ";
  1021.     private static String buildReaderWrongClassMsg(Object o) {
  1022.         return "(reader wrong class: "+o.getClass().getName()+")";
  1023.     }
  1024.     private static String buildExtractorWrongClassMsg(Object o) {
  1025.         return "(extractor wrong class: "+o.getClass().getName()+")";
  1026.     }
  1027.    
  1028.     // *** FREEMARKER ***
  1029.    
  1030.     public static void convertFreeMarkerTemplate(Template template,
  1031.             Map<String,Object> dynamicMap, OutputStream out) throws DynamicException {
  1032.         convertFreeMarkerTemplate(template,
  1033.                 dynamicMap, out, null);
  1034.     }
  1035.     public static void convertFreeMarkerTemplate(Template template,
  1036.             Map<String,Object> dynamicMap, OutputStream out, String charset) throws DynamicException {
  1037.         try {          
  1038.             OutputStreamWriter oow = null;
  1039.             if(charset!=null) {
  1040.                 oow = new OutputStreamWriter(out, charset);
  1041.             }
  1042.             else {
  1043.                 oow = new OutputStreamWriter(out);
  1044.             }
  1045.             convertFreeMarkerTemplateEngine(template,
  1046.                     dynamicMap, oow);
  1047.             oow.flush();
  1048.             oow.close();
  1049.         }catch(Exception e) {
  1050.             throw new DynamicException(e.getMessage(),e);
  1051.         }
  1052.     }
  1053.    
  1054.     public static void convertFreeMarkerTemplate(Template template,
  1055.             Map<String,Object> dynamicMap, Writer writer) throws DynamicException {
  1056.         convertFreeMarkerTemplateEngine(template,
  1057.                 dynamicMap, writer);
  1058.     }
  1059.    
  1060.     public static void convertZipFreeMarkerTemplate(ZipTemplate zipTemplate,
  1061.             Map<String,Object> dynamicMap, OutputStream out) throws DynamicException {
  1062.         convertZipFreeMarkerTemplate(zipTemplate,
  1063.                 dynamicMap, out, null);
  1064.     }
  1065.     public static void convertZipFreeMarkerTemplate(ZipTemplate zipTemplate,
  1066.             Map<String,Object> dynamicMap, OutputStream out, String charset) throws DynamicException {
  1067.         try {          
  1068.             OutputStreamWriter oow = null;
  1069.             if(charset!=null) {
  1070.                 oow = new OutputStreamWriter(out, charset);
  1071.             }
  1072.             else {
  1073.                 oow = new OutputStreamWriter(out);
  1074.             }
  1075.             convertZipFreeMarkerTemplate(zipTemplate,  
  1076.                     dynamicMap, oow);
  1077.             oow.flush();
  1078.             oow.close();
  1079.         }catch(Exception e) {
  1080.             throw new DynamicException(e.getMessage(),e);
  1081.         }
  1082.     }
  1083.     public static void convertZipFreeMarkerTemplate(ZipTemplate zipTemplate,
  1084.             Map<String,Object> dynamicMap, Writer writer) throws DynamicException {
  1085.        
  1086.         Template template = zipTemplate.getTemplateFreeMarker();
  1087.        
  1088.         convertFreeMarkerTemplateEngine(template,
  1089.                 dynamicMap, writer);
  1090.     }
  1091.    
  1092.     private static void convertFreeMarkerTemplateEngine(Template template,
  1093.             Map<String,Object> dynamicMap, Writer writer) throws DynamicException {
  1094.         try {
  1095.             // ** Aggiungo utility per usare metodi statici ed istanziare oggetti
  1096.            
  1097.             // statici
  1098.             BeansWrapper wrapper = new BeansWrapper(Configuration.VERSION_2_3_23);
  1099.             TemplateModel classModel = wrapper.getStaticModels();
  1100.             dynamicMap.put(Costanti.MAP_CLASS_LOAD_STATIC, classModel);
  1101.            
  1102.             // newObject
  1103.             dynamicMap.put(Costanti.MAP_CLASS_NEW_INSTANCE, new freemarker.template.utility.ObjectConstructor());
  1104.            
  1105.             // ** costruisco template
  1106.             freemarker.template.Template templateFTL = template.getTemplateFreeMarker();
  1107.            
  1108.             // ** applico trasformazione
  1109.             templateFTL.process(dynamicMap, writer);
  1110.             writer.flush();
  1111.            
  1112.         }catch(Exception e) {
  1113.             throw new DynamicException(e.getMessage(),e);
  1114.         }
  1115.     }
  1116.    
  1117.     public static freemarker.template.Template buildFreeMarkerTemplate(Template template) throws DynamicException {
  1118.         try {
  1119.             String name = template.getName();
  1120.             byte[] templateBin = template.getTemplate();
  1121.             Map<String, byte[]> templateIncludes = template.getTemplateIncludes();
  1122.            
  1123.             // Configurazione
  1124.             freemarker.template.Configuration config = TemplateUtils.newTemplateEngine();
  1125.             config.setAPIBuiltinEnabled(true); // serve per modificare le mappe in freemarker
  1126.            
  1127.             // template includes
  1128.             if(templateIncludes!=null && !templateIncludes.isEmpty()) {
  1129.                 config.setTemplateLoader(new FreemarkerTemplateLoader(templateIncludes));
  1130.             }
  1131.            
  1132.             // costruisco template
  1133.             return TemplateUtils.buildTemplate(config, name, templateBin);
  1134.            
  1135.         }catch(Exception e) {
  1136.             throw new DynamicException(e.getMessage(),e);
  1137.         }
  1138.     }
  1139.    
  1140.    
  1141.    
  1142.     // *** VELOCITY ***
  1143.    
  1144.     public static void convertVelocityTemplate(Template template,
  1145.             Map<String,Object> dynamicMap, OutputStream out) throws DynamicException {
  1146.         convertVelocityTemplate(template,
  1147.                 dynamicMap, out, null);
  1148.     }
  1149.     public static void convertVelocityTemplate(Template template,
  1150.             Map<String,Object> dynamicMap, OutputStream out, String charset) throws DynamicException {
  1151.         try {
  1152.             OutputStreamWriter oow = null;
  1153.             if(charset!=null) {
  1154.                 oow = new OutputStreamWriter(out, charset);
  1155.             }
  1156.             else {
  1157.                 oow = new OutputStreamWriter(out);
  1158.             }
  1159.             convertVelocityTemplateEngine(template,
  1160.                     dynamicMap, oow);
  1161.             oow.flush();
  1162.             oow.close();
  1163.         }catch(Exception e) {
  1164.             throw new DynamicException(e.getMessage(),e);
  1165.         }
  1166.     }
  1167.    
  1168.     public static void convertVelocityTemplate(Template template,
  1169.             Map<String,Object> dynamicMap, Writer writer) throws DynamicException {
  1170.         convertVelocityTemplateEngine(template,
  1171.                 dynamicMap, writer);
  1172.     }
  1173.    
  1174.     public static void convertZipVelocityTemplate(ZipTemplate zipTemplate,
  1175.             Map<String,Object> dynamicMap, OutputStream out) throws DynamicException {
  1176.         convertZipVelocityTemplate(zipTemplate,
  1177.                 dynamicMap, out, null);
  1178.     }
  1179.     public static void convertZipVelocityTemplate(ZipTemplate zipTemplate,
  1180.             Map<String,Object> dynamicMap, OutputStream out, String charset) throws DynamicException {
  1181.         try {          
  1182.             OutputStreamWriter oow = null;
  1183.             if(charset!=null) {
  1184.                 oow = new OutputStreamWriter(out, charset);
  1185.             }
  1186.             else {
  1187.                 oow = new OutputStreamWriter(out);
  1188.             }
  1189.             convertZipVelocityTemplate(zipTemplate,  
  1190.                     dynamicMap, oow);
  1191.             oow.flush();
  1192.             oow.close();
  1193.         }catch(Exception e) {
  1194.             throw new DynamicException(e.getMessage(),e);
  1195.         }
  1196.     }
  1197.     public static void convertZipVelocityTemplate(ZipTemplate zipTemplate,
  1198.             Map<String,Object> dynamicMap, Writer writer) throws DynamicException {
  1199.        
  1200.         Template template = zipTemplate.getTemplateFreeMarker();
  1201.        
  1202.         convertVelocityTemplateEngine(template,
  1203.                 dynamicMap, writer);
  1204.     }
  1205.    
  1206.     private static void convertVelocityTemplateEngine(Template template,
  1207.             Map<String,Object> dynamicMap, Writer writer) throws DynamicException {
  1208.         try {
  1209.             // ** Aggiungo utility per usare metodi statici ed istanziare oggetti
  1210.            
  1211.             // statici
  1212.             dynamicMap.put(Costanti.MAP_CLASS_LOAD_STATIC, "".getClass());
  1213.            
  1214.             // newObject
  1215.             dynamicMap.put(Costanti.MAP_CLASS_NEW_INSTANCE, new ObjectConstructor());
  1216.            
  1217.             // ** costruisco template
  1218.             org.apache.velocity.Template templateVelocity = template.getTemplateVelocity();
  1219.            
  1220.             // ** applico trasformazione
  1221.             templateVelocity.merge(VelocityTemplateUtils.toVelocityContext(dynamicMap), writer);
  1222.             writer.flush();
  1223.            
  1224.         }catch(Exception e) {
  1225.             throw new DynamicException(e.getMessage(),e);
  1226.         }
  1227.     }
  1228.    
  1229.     public static org.apache.velocity.Template buildVelocityTemplate(Template template) throws DynamicException {
  1230.         try {
  1231.             String name = template.getName();
  1232.             byte[] templateBin = template.getTemplate();
  1233.             Map<String, byte[]> templateIncludes = template.getTemplateIncludes();
  1234.            
  1235.             // Configurazione
  1236.             return VelocityTemplateUtils.buildTemplate(name, templateBin, templateIncludes);
  1237.                    
  1238.         }catch(Exception e) {
  1239.             throw new DynamicException(e.getMessage(),e);
  1240.         }
  1241.     }
  1242.        
  1243.    
  1244.    
  1245.     // *** XSLT ***
  1246.    
  1247.     private static boolean xsltProcessAsDomSource = true;
  1248.    
  1249.     public static boolean isXsltProcessAsDomSource() {
  1250.         return xsltProcessAsDomSource;
  1251.     }
  1252.     public static void setXsltProcessAsDomSource(boolean xsltProcessAsDomSource) {
  1253.         DynamicUtils.xsltProcessAsDomSource = xsltProcessAsDomSource;
  1254.     }
  1255.     public static void convertXSLTTemplate(String name, byte[] template, Element element, OutputStream out) throws DynamicException {
  1256.         try {
  1257.             Source xsltSource = null;
  1258.             if(xsltProcessAsDomSource) {
  1259.                 xsltSource = new DOMSource(org.openspcoop2.utils.xml.XMLUtils.getInstance().newElement(template));  
  1260.             }
  1261.             else {
  1262.                 xsltSource = new StreamSource(new ByteArrayInputStream(template));
  1263.             }
  1264.             Source xmlSource = new DOMSource(element);
  1265.             Transformer trans = MessageXMLUtils.DEFAULT.getTransformerFactory().newTransformer(xsltSource);
  1266.             trans.transform(xmlSource, new StreamResult(out));
  1267.             out.flush();
  1268.         }catch(Exception e) {
  1269.             throw new DynamicException("["+name+"] "+e.getMessage(),e);
  1270.         }
  1271.     }
  1272.    
  1273.    
  1274.    
  1275.     // *** COMPRESS ***
  1276.    
  1277.     public static void convertCompressorTemplate(String name,byte[] template,Map<String,Object> dynamicMap,Context pddContext,
  1278.             ArchiveType archiveType, OutputStream out) throws DynamicException{
  1279.         try {
  1280.             try(ByteArrayInputStream bin = new ByteArrayInputStream(template)){
  1281.                 java.util.Properties p = new java.util.Properties();
  1282.                 p.load(bin);
  1283.                
  1284.                 ContentExtractor contentExtractor = null;
  1285.                 String ruolo = null;
  1286.                 if(dynamicMap.containsKey(Costanti.MAP_REQUEST)) {
  1287.                     contentExtractor = (ContentExtractor) dynamicMap.get(Costanti.MAP_REQUEST);
  1288.                     ruolo = "messaggio di richiesta";
  1289.                 }
  1290.                 else if(dynamicMap.containsKey(Costanti.MAP_RESPONSE)) {
  1291.                     contentExtractor = (ContentExtractor) dynamicMap.get(Costanti.MAP_RESPONSE);
  1292.                     ruolo = "messaggio di risposta";
  1293.                 }
  1294.                
  1295.                 List<Entry> listEntries = new ArrayList<>();
  1296.                
  1297.                 Enumeration<?> keys = p.keys();
  1298.                 while (keys.hasMoreElements()) {
  1299.                     String keyP = (String) keys.nextElement();
  1300.                     keyP = keyP.trim();
  1301.                    
  1302.                     String oggetto = "property-"+keyP;
  1303.                     String entryName = convertCompressorTemplateReadDynamicValueEntryName(oggetto, keyP, dynamicMap, pddContext);
  1304.                     String prefixError = "["+keyP+"] ";
  1305.                    
  1306.                     String valoreP = p.getProperty(keyP);
  1307.                     if(valoreP==null) {
  1308.                         throw new DynamicException(prefixError+"Nessun valore fornito per la proprietà");
  1309.                     }
  1310.                     valoreP = valoreP.trim();
  1311.                    
  1312.                     byte[] content = converCompressTemplateReadContent(prefixError, keyP, valoreP, contentExtractor, ruolo,
  1313.                             dynamicMap, pddContext);
  1314.                    
  1315.                     listEntries.add(new Entry(entryName, content));
  1316.                 }
  1317.                
  1318.                 out.write(CompressorUtilities.archive(listEntries, archiveType));
  1319.             }
  1320.         }catch(Exception e) {
  1321.             throw new DynamicException("["+name+"] "+e.getMessage(),e);
  1322.         }
  1323.        
  1324.     }
  1325.     private static byte[] converCompressTemplateReadContent(String prefixError, String keyP, String valoreP, ContentExtractor contentExtractor, String ruolo,
  1326.             Map<String,Object> dynamicMap,Context pddContext) throws DynamicException {
  1327.         byte[] content = null;
  1328.         if(Costanti.COMPRESS_CONTENT.equals(valoreP)) {
  1329.             if(contentExtractor==null || !contentExtractor.hasContent()) {
  1330.                 throw new DynamicException(prefixError+"Il "+ruolo+" non possiede un payload");
  1331.             }
  1332.             content = contentExtractor.getContent();
  1333.         }
  1334.         else if(Costanti.COMPRESS_ENVELOPE.equals(valoreP) ||
  1335.                 Costanti.COMPRESS_BODY.equals(valoreP) ||
  1336.                 Costanti.COMPRESS_ENVELOPE.equalsIgnoreCase(valoreP) ||
  1337.                 Costanti.COMPRESS_BODY.equalsIgnoreCase(valoreP)) {
  1338.             content = convertCompressorTemplateReadEnvelope(prefixError, valoreP, contentExtractor, ruolo);
  1339.         }
  1340.         else if(valoreP.startsWith(Costanti.COMPRESS_ATTACH_PREFIX) ||
  1341.                 valoreP.startsWith(Costanti.COMPRESS_ATTACH_BY_ID_PREFIX) &&
  1342.                 valoreP.endsWith(Costanti.COMPRESS_SUFFIX)) {
  1343.             content = convertCompressorTemplateReadAttachContent(prefixError, valoreP, contentExtractor, ruolo);
  1344.         }
  1345.         else {
  1346.             String oggettoV = "valore-"+keyP;
  1347.             content = convertCompressorTemplateReadDynamicContent(prefixError, oggettoV, valoreP, dynamicMap, pddContext);
  1348.         }
  1349.        
  1350.         if(content==null || content.length==0) {
  1351.             throw new DynamicException(prefixError+"Nessun contenuto da associare alla entry trovato");
  1352.         }
  1353.         return content;
  1354.     }
  1355.     private static int converCompressTemplateReadAttachmentIndex(String prefixError, String valoreInterno) throws DynamicException {
  1356.         int index = -1;
  1357.         try {
  1358.             index = Integer.valueOf(valoreInterno);
  1359.         }catch(Exception e) {
  1360.             throw new DynamicException(prefixError+"L'indice definito per l'attachment non è un numero intero: "+e.getMessage(),e);
  1361.         }
  1362.         return index;
  1363.     }
  1364.     private static String convertCompressorTemplateReadDynamicValueEntryName(String oggetto, String key, Map<String,Object> dynamicMap,Context pddContext) throws DynamicException {
  1365.         try {
  1366.             return DynamicUtils.convertDynamicPropertyValue(oggetto, key, dynamicMap, pddContext);
  1367.         }catch(Exception e) {
  1368.             throw new DynamicException("["+oggetto+"] Conversione valore per entry name '"+key+"' non riuscita: "+e.getMessage(),e);
  1369.         }
  1370.     }
  1371.     private static byte[] convertCompressorTemplateReadEnvelope(String prefixError, String valoreP, ContentExtractor contentExtractor, String ruolo) throws DynamicException {
  1372.         byte[] content = null;
  1373.         if(contentExtractor==null || !contentExtractor.hasContent()) {
  1374.             throw new DynamicException(prefixError+"Il "+ruolo+" non possiede un payload");
  1375.         }
  1376.         if(!contentExtractor.isSoap()) {
  1377.             throw new DynamicException(prefixError+"Il "+ruolo+" non è un messaggio soap");
  1378.         }
  1379.         if(Costanti.COMPRESS_ENVELOPE.equals(valoreP) ||
  1380.                 Costanti.COMPRESS_ENVELOPE.equalsIgnoreCase(valoreP)) {
  1381.             DumpMessaggio dump = contentExtractor.dumpMessage();
  1382.             if(dump==null) {
  1383.                 throw new DynamicException(prefixError+"Dump del "+ruolo+" non disponibile");
  1384.             }
  1385.             content = dump.getBody();
  1386.         }
  1387.         else {
  1388.             content = contentExtractor.getContentSoapBody();
  1389.         }
  1390.         return content;
  1391.     }
  1392.     private static byte[] convertCompressorTemplateReadDynamicContent(String prefixError, String oggettoV, String valoreP, Map<String,Object> dynamicMap,Context pddContext) throws DynamicException {
  1393.         try {
  1394.             String v = DynamicUtils.convertDynamicPropertyValue(oggettoV, valoreP, dynamicMap, pddContext);
  1395.             if(v!=null) {
  1396.                 return v.getBytes();
  1397.             }
  1398.         }catch(Exception e) {
  1399.             throw new DynamicException(prefixError+"["+oggettoV+"] Conversione valore non riuscita: "+e.getMessage(),e);
  1400.         }
  1401.         return new byte[0];
  1402.     }
  1403.     private static byte[] convertCompressorTemplateReadAttachContent(String prefixError, String valoreP, ContentExtractor contentExtractor, String ruolo) throws DynamicException {
  1404.         String valoreInterno = valoreP.substring(Costanti.COMPRESS_ATTACH_PREFIX.length(), valoreP.length()-1);
  1405.         if(valoreInterno==null || "".equals(valoreInterno)) {
  1406.             throw new DynamicException(prefixError+"Non è stato definito un indice per l'attachment");
  1407.         }
  1408.         DumpMessaggio dump = contentExtractor.dumpMessage();
  1409.         if(dump==null) {
  1410.             throw new DynamicException(prefixError+"Dump del "+ruolo+" non disponibile");
  1411.         }
  1412.        
  1413.         DumpAttachment attach = null;
  1414.         boolean attachAtteso = true;
  1415.         byte[] content = null;
  1416.         if(valoreP.startsWith(Costanti.COMPRESS_ATTACH_PREFIX)) {
  1417.             int index = converCompressTemplateReadAttachmentIndex(prefixError, valoreInterno);
  1418.             if(contentExtractor.isRest() && index==0) {
  1419.                 content = dump.getBody();
  1420.                 attachAtteso = false;
  1421.             }
  1422.             else {
  1423.                 attach = convertCompressorTemplateReadDumpAttachment(dump, contentExtractor, index);
  1424.             }
  1425.         }
  1426.         else {
  1427.             if(contentExtractor.isRest() &&
  1428.                     dump.getMultipartInfoBody()!=null &&
  1429.                     valoreInterno.equals(dump.getMultipartInfoBody().getContentId())) {
  1430.                 content = dump.getBody();
  1431.                 attachAtteso = false;
  1432.             }
  1433.             else {
  1434.                 attach = dump.getAttachment(valoreInterno);
  1435.             }
  1436.         }
  1437.        
  1438.         if(attachAtteso) {
  1439.             content = convertCompressorTemplateReadAttachContent(prefixError, attach);
  1440.         }
  1441.        
  1442.         return content;
  1443.     }
  1444.     private static DumpAttachment convertCompressorTemplateReadDumpAttachment(DumpMessaggio dump, ContentExtractor contentExtractor, int index) {
  1445.         DumpAttachment attach = null;
  1446.         if(contentExtractor.isRest()) {
  1447.             attach = dump.getAttachment((index-1));
  1448.         }
  1449.         else {
  1450.             attach = dump.getAttachment(index);
  1451.         }
  1452.         return attach;
  1453.     }
  1454.     private static byte[] convertCompressorTemplateReadAttachContent(String prefixError, DumpAttachment attach) throws DynamicException{
  1455.         byte[] content = null;
  1456.         if(attach==null) {
  1457.             throw new DynamicException(prefixError+"L'indice definito per l'attachment non ha identificato alcun attachment");
  1458.         }
  1459.         content = attach.getContent();
  1460.         return content;
  1461.     }

  1462. }

  1463. enum TemplateType {
  1464.    
  1465.     XML, JSON, URL, SYSTEM, ENV, JAVA, ENV_JAVA;
  1466.    
  1467. }