# QueryJasperDataSource.java

    /*
    ** Module   : QueryJasperDataSource.java
    ** Abstract : Data source for a FWD Jasper report backed by a query.
    **
    ** Copyright (c) 2018-2021, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
    ** 001 SVL 20180207 Created initial version.
    ** 002 EVL 20210305 Adding ability to have data source without fields.
    **     OM  20210309 Do not use DmoMeta as key in TableMapper because temp-tables might share the same
    **                  DmoMeta instance.
    **     SVL 20210809 Refactoring: moved getMatchingBufferField to DBUtils.
    */

    /*
    ** 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.reporting;

    import com.goldencode.p2j.*;
    import com.goldencode.p2j.persist.*;
    import com.goldencode.p2j.ui.client.format.*;
    import com.goldencode.p2j.util.*;
    import java.util.*;
    import net.sf.jasperreports.engine.*;

    import static com.goldencode.p2j.reporting.ReportFactory.showError;

    /**
     * Data source for a FWD Jasper report backed by a query.
     */
    class QueryJasperDataSource
    implements JasperDataSource
    {
       /** Query for getting report data. */
       private final QueryWrapper query;

       /** Map of Jasper report field names to 4GL fields. */
       private HashMap<String, BufferField> fieldMapping;

       /**
        * <code>true</code> if the query was already iterated by this data source and we already got
        * the first record in the result set.
        */
       private boolean iterated = false;

       /**
        * Create data source which gets the report data from the specified query.
        *
        * @param query
        *        Query for getting report data.
        */
       QueryJasperDataSource(QueryWrapper query)
       {
          this.query = query;
       }

       /**
        * Tries to position the cursor on the next element in the data source.
        *
        * @return <code>true</code> if there is a next record, <code>false</code> otherwise.
        *
        * @throws JRException
        *         if any error occurs while trying to move to the next element.
        */
       @Override
       public boolean next()
       throws JRException
       {
          if (!iterated)
          {
             iterated = true;
             return query.getFirst().booleanValue();
          }
          else
          {
             return query.getNext().booleanValue();
          }
       }

       /**
        * Gets the field value for the current position.
        *
        * @param  field
        *         Field to get.
        *
        * @return an object containing the field value. The object type must be the field object type.
        *
        * @throws JRException
        *         if any error occurs while trying to get the field value.
        */
       @Override
       public Object getFieldValue(JRField field)
       throws JRException
       {
          BufferField progressField = fieldMapping.get(field.getName());
          BaseDataType progressValue = progressField.value();
          return JasperReportWrapper.getJavaValue(progressValue, field.getValueClass());
       }

       /**
        * Get compiled Jasper report for the given report design file.
        *
        * @param  designFileName
        *         File name of the Jasper report design file.
        *
        * @return compiled Jasper report for the given report design file.
        */
       @Override
       public JasperReport getReport(String designFileName)
       {
          return ReportFactory.getReport(designFileName);
       }

       /**
        * Executed before report is filled from the data source.
        *
        * @param  report
        *         Jasper report to be filled.
        *
        * @return <code>true</code> on success, <code>false</code> if the data source cannot provide
        *         data.
        */
       @Override
       public boolean reportStarted(JasperReport report)
       {
          if (!query.isOpen().booleanValue())
          {
             showError("Query should be open before the report is run.");
             return false;
          }

          return buildFieldMapping(report);
       }

       /**
        * Executed after report was filled from the data source.
        *
        * @param  error
        *         <code>true</code> if there were problems while getting data from the data source.
        *         <code>false</code> on success,
        */
       @Override
       public void reportFinished(boolean error)
       {
       }

       /**
        * Get underlying 4GL query object which provides data for the report.
        *
        * @return handle to the underlying 4GL query object which provides data for the report.
        */
       @Override
       public handle asProgressObject()
       {
          return new handle(query);
       }

       /**
        * Build and store field mapping (Jasper report field names to 4GL fields) for the given
        * report.
        *
        * @param  report
        *         Jasper report for which we need to build a field mapping.
        *
        * @return <code>true</code> on success.
        */
       private boolean buildFieldMapping(JasperReport report)
       {
          fieldMapping = new HashMap<>();
          JRField[] allFields = report.getFields();
          // check the possibility to have any fields, no fields can also be valid
          if (allFields != null && allFields.length > 0)
          {
             for (JRField jrField : allFields)
             {
                BufferField progressField = getMatchingBufferField(jrField);
                if (progressField == null)
                {
                   // error was displayed by getMatchingBufferField
                   return false;
                }

                // validate field data types
                try
                {
                   BaseDataType progressBDT =
                         DisplayFormat.instanceOfType(progressField.getDataType().getValue());
                   JasperReportWrapper.getJavaValue(progressBDT, jrField.getValueClass());
                }
                catch (IllegalArgumentException e)
                {
                   showError("Invalid data type of report field " + jrField.getName(), e);
                   return false;
                }

                fieldMapping.put(jrField.getName(), progressField);
             }
          }

          return true;
       }

       /**
        * Get the 4GL buffer field matching the given Jasper report field. Search is performed by
        * report field name which should have format "4gl-buffer-name.4gl-field-name" or
        * "4gl-field-name". If explicit buffer name is not specified and query has multiple buffers
        * which have the field with the specified name, error is raised.
        *
        * @param   reportField
        *          Jasper report field.
        *
        * @return  matching 4GL buffer field or <code>null</code> if there is no matching field.
        */
       private BufferField getMatchingBufferField(JRField reportField)
       {
          String fullName = reportField.getName();

          try
          {
             return DBUtils.getMatchingBufferField(query, fullName);
          }
          catch (NumberedException e)
          {
             switch (e.getNumber())
             {
                case 1:
                   showError(String.format("There is no matching 4GL field for Jasper report field '%s'",
                         fullName));
                   break;
                case 2:
                   showError(String.format("There are multiple buffers with the field named '%s'. " +
                               "Specify buffer name explicitly using 'buffer-name.field-name' notation.",
                         fullName));
             }

             return null;
          }
       }
    }