JSonDeserializer.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.utils.serialization;

  21. import java.io.ByteArrayOutputStream;
  22. import java.io.InputStream;
  23. import java.io.Reader;
  24. import java.io.StringWriter;
  25. import java.lang.reflect.Method;
  26. import java.util.ArrayList;
  27. import java.util.List;
  28. import java.util.Set;

  29. import org.openspcoop2.utils.CopyCharStream;
  30. import org.openspcoop2.utils.CopyStream;
  31. import org.openspcoop2.utils.UtilsException;
  32. import org.openspcoop2.utils.resources.ClassLoaderUtilities;

  33. import net.sf.ezmorph.MorpherRegistry;
  34. import net.sf.json.JSONArray;
  35. import net.sf.json.JSONObject;
  36. import net.sf.json.JsonConfig;
  37. import net.sf.json.util.JSONUtils;

  38. /**
  39.  * Contiene utility per effettuare la de-serializzazione di un oggetto
  40.  *
  41.  * @author Poli Andrea (apoli@link.it)
  42.  * @author $Author$
  43.  * @version $Rev$, $Date$
  44.  */

  45. public class JSonDeserializer implements IDeserializer{

  46.    
  47.     private JsonConfig jsonConfig;
  48.     private List<String> morpherPackage = new ArrayList<>();
  49.     private boolean throwExceptionMorpherFailed = true;
  50.    
  51.     public JSonDeserializer() {
  52.         this(new SerializationConfig());
  53.     }
  54.    
  55.     public JSonDeserializer(SerializationConfig config) {
  56.         JsonConfig jsonConfig = new JsonConfig();
  57.         if(config.getExcludes()!=null){
  58.             //jsonConfig.setExcludes(excludes); non funziona l'exclude durante la deserializzazione, uso un filtro
  59.             jsonConfig.setJavaPropertyFilter(new ExclusionPropertyFilter(config.getExcludes()));
  60.         }
  61.         this.jsonConfig = jsonConfig;
  62.         this.addMorpherPackage("org.openspcoop2");
  63.     }
  64.    
  65.     public void addMorpherPackage(String p){
  66.         this.morpherPackage.add(p);
  67.     }
  68.    
  69.     public boolean isThrowExceptionMorpherFailed() {
  70.         return this.throwExceptionMorpherFailed;
  71.     }
  72.     public void setThrowExceptionMorpherFailed(boolean throwExceptionMorpherFailed) {
  73.         this.throwExceptionMorpherFailed = throwExceptionMorpherFailed;
  74.     }
  75.    
  76.     @Override
  77.     public Object getObject(String s, Class<?> classType) throws IOException{
  78.         return getObject(s, classType, null);
  79.     }
  80.     public Object getListObject(String s, Class<?> listType, Class<?> elementsTypes) throws IOException{
  81.         Object o = getObject(s, listType, elementsTypes);
  82.         if( !(o instanceof List) ){
  83.             throw new IOException("Object de-serializzato di tipo non java.util.List: "+o.getClass().getName());
  84.         }
  85.         return o;
  86.     }
  87.     public Object getSetObject(String s, Class<?> setType, Class<?> elementsTypes) throws IOException{
  88.         Object o = getObject(s, setType, elementsTypes);
  89.         if( !(o instanceof Set) ){
  90.             throw new IOException("Object de-serializzato di tipo non java.util.Set: "+o.getClass().getName());
  91.         }
  92.         return o;
  93.     }
  94.     private Object getObject(String s, Class<?> classType, Class<?> elementsTypes ) throws IOException{
  95.         try{
  96.             return readObject_engine(s, classType, elementsTypes);  
  97.         }catch(Exception e){
  98.             throw new IOException("Trasformazione in oggetto non riuscita: "+e.getMessage(),e);
  99.         }
  100.     }
  101.    
  102.    
  103.    
  104.     @Override
  105.     public Object readObject(InputStream is, Class<?> classType) throws IOException{
  106.         return readObject(is, classType, null);
  107.     }
  108.     public Object readListObject(InputStream is, Class<?> listType, Class<?> elementsTypes) throws IOException{
  109.         Object o = readObject(is, listType, elementsTypes);
  110.         if( !(o instanceof List) ){
  111.             throw new IOException("Object de-serializzato di tipo non java.util.List: "+o.getClass().getName());
  112.         }
  113.         return o;
  114.     }
  115.     public Object readSetObject(InputStream is, Class<?> setType, Class<?> elementsTypes) throws IOException{
  116.         Object o = readObject(is, setType, elementsTypes);
  117.         if( !(o instanceof Set) ){
  118.             throw new IOException("Object de-serializzato di tipo non java.util.Set: "+o.getClass().getName());
  119.         }
  120.         return o;
  121.     }
  122.     private Object readObject(InputStream is, Class<?> classType, Class<?> elementsTypes) throws IOException{
  123.         try{
  124.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  125. //          byte [] reads = new byte[Utilities.DIMENSIONE_BUFFER];
  126. //          int letti = 0;
  127. //          while( (letti=is.read(reads)) != -1 ){
  128. //              bout.write(reads, 0, letti);
  129. //          }
  130.             CopyStream.copy(is, bout);
  131.             bout.flush();
  132.             bout.close();
  133.            
  134.             return readObject_engine(bout.toString(), classType, elementsTypes);    
  135.            
  136.         }catch(Exception e){
  137.             throw new IOException("Trasformazione in oggetto non riuscita: "+e.getMessage(),e);
  138.         }
  139.     }
  140.    
  141.    
  142.    
  143.     @Override
  144.     public Object readObject(Reader reader, Class<?> classType) throws IOException{
  145.         return readObject(reader, classType, null);
  146.     }
  147.     public Object readListObject(Reader reader, Class<?> listType, Class<?> elementsTypes) throws IOException{
  148.         Object o = readObject(reader, listType, elementsTypes);
  149.         if( !(o instanceof List) ){
  150.             throw new IOException("Object de-serializzato di tipo non java.util.List: "+o.getClass().getName());
  151.         }
  152.         return o;
  153.     }
  154.     public Object readSetObject(Reader reader, Class<?> setType, Class<?> elementsTypes) throws IOException{
  155.         Object o = readObject(reader, setType, elementsTypes);
  156.         if( !(o instanceof Set) ){
  157.             throw new IOException("Object de-serializzato di tipo non java.util.Set: "+o.getClass().getName());
  158.         }
  159.         return o;
  160.     }
  161.     private Object readObject(Reader reader, Class<?> classType, Class<?> elementsTypes) throws IOException{
  162.         try{
  163. //          char [] reads = new char[Utilities.DIMENSIONE_BUFFER];
  164. //          int letti = 0;
  165. //          StringBuilder bf = new StringBuilder();
  166. //          while( (letti=reader.read(reads)) != -1 ){
  167. //              bf.append(reads, 0, letti);
  168. //          }
  169. //          
  170.             StringWriter writer = new StringWriter();
  171.             CopyCharStream.copy(reader, writer);
  172.                        
  173.             return readObject_engine(writer.toString(), classType, elementsTypes);  
  174.            
  175.         }catch(Exception e){
  176.             throw new IOException("Trasformazione in oggetto non riuscita: "+e.getMessage(),e);
  177.         }
  178.     }

  179.    
  180.    
  181.     private Object readObject_engine(String object,Class<?> classType, Class<?> elementsTypes) throws Exception{
  182.        
  183.         boolean list = false;
  184.         try{
  185.             classType.asSubclass(List.class);
  186.             list = true;
  187.         }catch(ClassCastException cc){}
  188.        
  189.         boolean set = false;
  190.         try{
  191.             classType.asSubclass(Set.class);
  192.             set = true;
  193.         }catch(ClassCastException cc){}
  194.        
  195.         //System.out.println("CLASS: "+classType.getName() +" ENUM["+classType.isEnum()+"] ARRAY["+classType.isArray()+"] LISTCAST["+list+"] SETCAST["+set+"]");
  196.        
  197.         if(classType.isEnum()){
  198.             JSONArray jsonArray = JSONArray.fromObject( object );
  199.             Object en = jsonArray.toArray()[0];
  200.             //System.out.println("TIPO ["+en.getClass().getName()+"]");
  201.             Object [] o = classType.getEnumConstants();
  202.             Class<?> enumeration = o[0].getClass();
  203.             //System.out.println("OO ["+enumeration+"]");
  204.             Method method = enumeration.getMethod("valueOf", String.class);
  205.             Object value = method.invoke(enumeration, en);
  206.             return value;
  207.         }
  208.        
  209.         else if(classType.isArray()){

  210.             JSONArray jsonArray = JSONArray.fromObject( object );
  211.             Object[] oarray = jsonArray.toArray();
  212.             Object[] array = new Object[oarray.length];
  213.             for(int i=0; i<oarray.length;i++){
  214.                 JSONObject json = (JSONObject) oarray[i];
  215.                 array[i] =  fromJSONObjectToOriginalObject(classType.getComponentType(), json);
  216.             }
  217.             return array;
  218.         }
  219.        
  220.         else if(list){
  221.            
  222.             if(elementsTypes==null){
  223.                 throw new Exception("elementsTypes non definito, e' obbligatorio per il tipo che si desidera de-serializzare: "+classType.getName());
  224.             }
  225.            
  226.             JSONArray jsonArray = JSONArray.fromObject( object );
  227.             Object[] oarray = jsonArray.toArray();
  228.             @SuppressWarnings("unchecked")
  229.             List<Object> listReturn = (List<Object>) ClassLoaderUtilities.newInstance(classType);      
  230.             for(int i=0; i<oarray.length;i++){
  231.                 JSONObject json = (JSONObject) oarray[i];
  232.                 Object o =  fromJSONObjectToOriginalObject(elementsTypes, json);
  233.                 listReturn.add(o);
  234.             }
  235.             return listReturn;
  236.         }
  237.        
  238.         else if(set){
  239.            
  240.             if(elementsTypes==null){
  241.                 throw new Exception("elementsTypes non definito, e' obbligatorio per il tipo che si desidera de-serializzare: "+classType.getName());
  242.             }
  243.            
  244.             JSONArray jsonArray = JSONArray.fromObject( object );
  245.             Object[] oarray = jsonArray.toArray();
  246.             @SuppressWarnings("unchecked")
  247.             Set<Object> setReturn = (Set<Object>) ClassLoaderUtilities.newInstance(classType);      
  248.             for(int i=0; i<oarray.length;i++){
  249.                 JSONObject json = (JSONObject) oarray[i];
  250.                 Object o =  fromJSONObjectToOriginalObject(elementsTypes, json);
  251.                 setReturn.add(o);
  252.             }
  253.             return setReturn;
  254.         }
  255.        
  256.         else{
  257.             JSONObject jsonObject = JSONObject.fromObject( object );  
  258.             return fromJSONObjectToOriginalObject(classType, jsonObject);
  259.         }
  260.     }
  261.    
  262.     private Object fromJSONObjectToOriginalObject(Class<?> classType, JSONObject jsonObject) throws UtilsException{
  263.         this.jsonConfig.setRootClass(classType);
  264.        
  265.         MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry();
  266.         org.openspcoop2.utils.serialization.Utilities.registerMorpher(classType, morpherRegistry, new ArrayList<>(), this.morpherPackage);
  267.        
  268.         Object o = JSONObject.toBean( jsonObject, this.jsonConfig );

  269.         org.openspcoop2.utils.serialization.Utilities.morpher(o, morpherRegistry, this.morpherPackage, this.throwExceptionMorpherFailed);
  270.        
  271.         return o;
  272.     }
  273.    
  274. }