# SortIndex.java

    /*
    ** Module   : SortIndex.java
    ** Abstract : Object which indicates the type of sort used for a particular
    **            query
    **
    ** Copyright (c) 2004-2022, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- --JPRM-- -----------------------------------Description-----------------------------------
    ** 001 ECF 20071206  @36264  Created initial version. Object which indicates the type of sort used
    **                           for a particular query, without regard for sort direction (ascending
    **                           or descending).
    ** 002 SVL 20080418  @38025  Added isInverseSortPhrase(..) function. Into the create(..) method
    **                           the sortPhrase is parsed with makeUnique set to false.
    ** 003 ECF 20150315          Intern strings.
    ** 004 CA  20221102          Made the class public, as is required for AOP method tracing (see
    **                           p2j.aspects.ltw.MethodTraceAspect).
    */
    /*
    ** 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;

    import java.util.*;

    /**
     * An object which indicates the type of sort used for a particular query,
     * without regard for sort direction (ascending or descending).  For example,
     * the following sort phrases are inverses of one another, and would resolve
     * to the same instance of this class:
     * <pre>
     *    myDMO.customerNumber asc, myDMO.customerName asc, myDMO.key desc
     * </pre>
     * and
     * <pre>
     *    myDMO.customerNumber desc, myDMO.customerName desc, myDMO.key asc
     * </pre>
     * <p>
     * All instances of this class are immutable and are stored in a cache which
     * is shared across user contexts.
     * <p>
     * This information is used in combination with query off-end status, to
     * ensure dynamic queries start their searches at the appropriate record.
     *
     * @see  OffEnd
     * @see  RecordBuffer#getOffEnd(SortIndex, boolean)
     */
    public final class SortIndex
    {
       /** Shared cache of all <code>SortIndex</code> instances */
       private static final Map<String, SortIndex> cache = new HashMap<>();

       /** A sort index phrase whose leading component is ascending */
       private final String phrase;

       /** Inverse of {@link #phrase}, in terms of sort direction */
       private final String inverse;

       /**
        * Construct a new sort index, specifying a sort phrase and its directional
        * inverse.
        *
        * @param   phrase
        *          A raw sort index phrase (without upper/rtrim functions).
        * @param   inverse
        *          Inverse of <code>phrase</code>, in terms of sort direction.
        */
       private SortIndex(String phrase, String inverse)
       {
          this.phrase = phrase.intern();
          this.inverse = inverse.intern();
       }

       /**
        * Get an instance of this class which matches the given sort phrase.
        * <code>sortPhrase</code> may match either phrase stored in a
        * <code>SortIndex</code> instance (i.e., <code>phrase</code> or
        * <code>inverse</code>.  If an instance already exists, it is returned
        * from the shared cache;  otherwise, it is created and cached.
        *
        * @param   sortPhrase
        *          A sort phrase which indicates qualified DMO property name(s)
        *          and the respective direction(s) in which to sort (asc or desc).
        * @param   buffer
        *          The record buffer associated with the DMO property name(s) to
        *          be sorted.
        *
        * @return  An immutable, shared <code>SortIndex</code> instance.
        *
        * @throws  PersistenceException
        *          if a new instance must be created, and there is an error
        *          parsing <code>sortPhrase</code>.
        */
       static SortIndex get(String sortPhrase, RecordBuffer buffer)
       throws PersistenceException
       {
          SortIndex index = null;

          synchronized (cache)
          {
             index = cache.get(sortPhrase);
             if (index == null)
             {
                index = create(sortPhrase, buffer);
                cache.put(index.phrase, index);
                cache.put(index.inverse, index);
             }
          }

          return index;
       }

       /**
        * Create an instance of this class for the given sort phrase and its
        * inverse.  The primary sort phrase stored in this object will be the one
        * whose leading component sorts in ascending order;  the inverse sort
        * phrase will be the one whose leading component sorts in descending
        * order.
        *
        * @param   sortPhrase
        *          A sort phrase which indicates qualified DMO property name(s)
        *          and the respective direction(s) in which to sort (asc or desc).
        * @param   buffer
        *          The record buffer associated with the DMO property name(s) to
        *          be sorted.
        *
        * @return  An immutable, shared <code>SortIndex</code> instance.
        *
        * @throws  PersistenceException
        *          if a new instance must be created, and there is an error
        *          parsing <code>sortPhrase</code>.
        */
       private static SortIndex create(String sortPhrase, RecordBuffer buffer)
       throws PersistenceException
       {
          @SuppressWarnings("unchecked")
          List<SortCriterion> criteria = SortCriterion.parse(sortPhrase, buffer, false);
          String a = SortCriterion.assembleHQLNoPreamble(criteria, false);
          String b = SortCriterion.assembleHQLNoPreamble(criteria, true);

          return (a.compareTo(b) < 0 ? new SortIndex(a, b) : new SortIndex(b, a));
       }

       /**
        * Ensure an identity-based hash code is produced for this object.
        * <p>
        * This is appropriate because each unique instance of this class is
        * immutable and shared.  That is, two instances with the same primary
        * sort phrase should never exist in a single JVM instance.
        *
        * @see java.lang.Object#hashCode()
        */
       public final int hashCode()
       {
          return super.hashCode();
       }

       /**
        * Ensure an identity-based equality algorithm is employed when comparing
        * this object with others.
        * <p>
        * This is appropriate because each unique instance of this class is
        * immutable and shared.  That is, two instances with the same primary
        * sort phrase should never exist in a single JVM instance.
        *
        * @see java.lang.Object#equals(java.lang.Object)
        */
       public final boolean equals(Object obj)
       {
          return super.equals(obj);
       }

       /**
        * Compares the specified sort phrase with the inverse sort phrase of
        * this <code>SortIndex</code>.
        *
        * @param  sort
        *         Sort phrase to compare.
        * @return <code>true</code> if the specified sort phase equals the inverse
        *         sort phrase of this <code>SortIndex</code>.
        */
       public boolean isInverseSortPhrase(String sort)
       {
          return inverse.equals(sort);
       }
    }