StreamJsonSerializer.java

/*
** Module   : StreamJsonSerializer.java
** Abstract : Json stream serialization.
**
** Copyright (c) 2019-2023, Golden Code Development Corporation.
**
** -#- -I- --Date-- ----------------------------------------Description---------------------------------------
** 001 HC  20190707 Initial version.
**     OM  20190709 The backing stream can now be flushed and closed. Fixed decimal formatting.
** 002 CA  20190724 Fixed rawDecimalValue - it needs to write a value, and not 'raw'.
**     CA  20190812 rawDecimalValue - removed the '.0' - not clear why this was added in the first
**                  place.
** 003 CA  20210709 Force non-scientific format for BigDecimal numbers.
** 004 GBB 20230512 Logging methods replaced by CentralLogger/ConversionStatus.
*/

/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Affero General Public License for more details.
**
** You may find a copy of the GNU Affero GPL version 3 at the following
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
**
** Additional terms under GNU Affero GPL version 3 section 7:
**
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
**   terms apply to the works covered under the License.  These additional terms
**   are non-permissive additional terms allowed under Section 7 of the GNU
**   Affero GPL version 3 and may not be removed by you.
**
**   0. Attribution Requirement.
**
**     You must preserve all legal notices or author attributions in the covered
**     work or Appropriate Legal Notices displayed by works containing the covered
**     work.  You may not remove from the covered work any author or developer
**     credit already included within the covered work.
**
**   1. No License To Use Trademarks.
**
**     This license does not grant any license or rights to use the trademarks
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
**     of Golden Code Development Corporation. You are not authorized to use the
**     name Golden Code, FWD, or the names of any author or contributor, for
**     publicity purposes without written authorization.
**
**   2. No Misrepresentation of Affiliation.
**
**     You may not represent yourself as Golden Code Development Corporation or FWD.
**
**     You may not represent yourself for publicity purposes as associated with
**     Golden Code Development Corporation, FWD, or any author or contributor to
**     the covered work, without written authorization.
**
**   3. No Misrepresentation of Source or Origin.
**
**     You may not represent the covered work as solely your work.  All modified
**     versions of the covered work must be marked in a reasonable way to make it
**     clear that the modified work is not originating from Golden Code Development
**     Corporation or FWD.  All modified versions must contain the notices of
**     attribution required in this license.
*/
package com.goldencode.p2j.persist.serial;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.core.util.*;
import com.fasterxml.jackson.databind.*;
import com.goldencode.p2j.util.logging.*;

import java.io.*;
import java.math.*;

/**
 * Serializes json structure to a stream.
 */
public class StreamJsonSerializer
implements JsonStructureCallback
{
   /** Logger */
   private static final CentralLogger LOG = CentralLogger.get(StreamJsonSerializer.class);
   
   /** Jackson json generator */
   private JsonGenerator gen;

   /**
    * Constructor.
    *
    * @param   out
    *          Output stream.
    * @param   encoding
    *          Character encoding.
    * @param   pretty
    *          Pretty print flag.
    *
    * @throws  IOException
    *          when IO error occurs.
    */
   public StreamJsonSerializer(OutputStream out, JsonEncoding encoding, boolean pretty)
   throws IOException
   {
      ObjectMapper mapper = new ObjectMapper();
      mapper.configure(Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
      JsonFactory factory = mapper.getFactory();
      gen = factory.createGenerator(out, encoding);
      if (pretty)
      {
         // The way 4GL formats JSON is really strange. This small change makes it a bit easy to
         // spot changes allowing at least records on consecutive lines to be identically as 4GL
         gen.setPrettyPrinter(new DefaultPrettyPrinter()
         {
            /** 
             * Method called after an object field has been output, but before the value is
             * output.
             */
            public void writeObjectFieldValueSeparator(JsonGenerator jg)
            throws IOException
            {
               jg.writeRaw(": ");
            }
         });
      }
      else
      {
         gen.setPrettyPrinter(new MinimalPrettyPrinter());
      }
   }
   
   /**
    * Close the stream. Closes the internal stream.
    * 
    * @throws  IOException
    *          when IO error occurs.
    */
   public void closeStream()
   throws IOException
   {
      gen.close();
   }
   
   /**
    * Called when json object start is encountered.
    */
   @Override
   public void startObject()
   {
      try
      {
         gen.writeStartObject();
      }
      catch (IOException e)
      {
         LOG.info("", e);
      }
   }

   /**
    * Called when json object end is encountered.
    */
   @Override
   public void endObject()
   {
      try
      {
         gen.writeEndObject();
      }
      catch (IOException e)
      {
         LOG.info("", e);
      }
   }

   /**
    * Called when json array start is encountered.
    */
   @Override
   public void startArray()
   {
      try
      {
         gen.writeStartArray();
      }
      catch (IOException e)
      {
         LOG.info("", e);
      }
   }

   /**
    * Called when json array end is encountered.
    */
   @Override
   public void endArray()
   {
      try
      {
         gen.writeEndArray();
      }
      catch (IOException e)
      {
         LOG.info("", e);
      }
   }

   /**
    * Called when json field is encountered.
    *
    * @param   name
    *          Field name.
    */
   @Override
   public void fieldName(String name)
   {
      try
      {
         gen.writeFieldName(name);
      }
      catch (IOException e)
      {
         LOG.info("", e);
      }
   }

   /**
    * Called when json boolean value is encountered.
    *
    * @param   value
    *          The value.
    */
   @Override
   public void booleanValue(boolean value)
   {
      try
      {
         gen.writeBoolean(value);
      }
      catch (IOException e)
      {
         LOG.info("", e);
      }
   }

   /**
    * Called when json string value is encountered.
    *
    * @param   value
    *          The value.
    */
   @Override
   public void stringValue(String value)
   {
      try
      {
         gen.writeString(value);
      }
      catch (IOException e)
      {
         LOG.info("", e);
      }
   }

   /**
    * Called when json number value is encountered.
    *
    * @param   value
    *          The value.
    */
   @Override
   public void numberValue(Number value)
   {
      try
      {
         if (value == null)
         {
            gen.writeNull();
         }
         else if (value instanceof Short)
         {
            gen.writeNumber((Short) value);
         }
         else if (value instanceof Integer)
         {
            gen.writeNumber((Integer) value);
         }
         else if (value instanceof Long)
         {
            gen.writeNumber((Long) value);
         }
         else if (value instanceof Double)
         {
            gen.writeNumber((Double) value);
         }
         else if (value instanceof Float)
         {
            gen.writeNumber((Float) value);
         }
         else if (value instanceof BigInteger)
         {
            gen.writeNumber((BigInteger) value);
         }
         else if (value instanceof BigDecimal)
         {
            gen.writeNumber((BigDecimal) value);
         }
         else
         {
            throw new RuntimeException("Unsupported number type " + value.getClass());
         }
      }
      catch (IOException e)
      {
         LOG.info("", e);
      }
   }

   /**
    * Called when json null value is encountered.
    */
   @Override
   public void nullValue()
   {
      try
      {
         gen.writeNull();
      }
      catch (IOException e)
      {
         LOG.severe("", e);
      }
   }

   /**
    * Called when json raw decimal value is encountered.
    *
    * @param   value
    *          The value.
    */
   @Override
   public void rawDecimalValue(String value)
   {
      try
      {
         if (value.indexOf('.') == -1)
         {
            // CA: why is this here? what specific case does this solve?
            // OM: the decimal numbers serialize by ABL always have the decimal point '.' (Ex: "42.0").
            //     the [BigDecimal] that we use will drop it if the decimals are null (Ex: "42").
            value += ".0";
         }
         
         gen.writeRawValue(value);
      }
      catch (IOException e)
      {
         LOG.info("", e);
      }
   }
}