001/*
002 * Copyright c 2018 Rusi Popov, MDA Tools.net All rights reserved.
003 *
004 * This program and the accompanying materials are made available under the terms of the
005 * Eclipse Public License v2.0 which accompanies this distribution, and is available at
006 * http://www.eclipse.org/legal/epl-v20.html
007 */
008package net.mdatools.modelant.core.operation.model.order;
009
010import java.util.IdentityHashMap;
011import java.util.Map;
012
013import javax.jmi.reflect.RefBaseObject;
014
015import net.mdatools.modelant.core.api.Order;
016import net.mdatools.modelant.core.operation.element.PrintModelElement;
017
018/**
019 * Compare model elements by their restricted print representations.
020 *
021 * Do not reuse the instances - this would cause memory leaks.
022 *
023 * The profiling identified this OrderBy clause to be the slowest one, therefore: <ul>
024 * <li> introduced internal caching of the printouts
025 * <li> introduced internal restriction of the elements to print
026 * </ul>
027 */
028public class OrderByPrint implements Order {
029
030  private static final PrintModelElement PRINT_MODEL_ELEMENT = new PrintModelElement();
031
032  private final Map<RefBaseObject, String> elementToPrintOutMap = new IdentityHashMap<>();
033
034  public int compare(RefBaseObject o1, RefBaseObject o2) {
035    String rep1;
036    String rep2;
037
038    rep1 = getPrintOut( o1 );
039    rep2 = getPrintOut( o2 );
040
041    return rep1.compareTo( rep2 );
042  }
043
044  /**
045   * The profiling identified this OrderBy clause to be the slowest one, therefore: <ul>
046   * <li> introduced internal caching of the printouts
047   * <li> introduced internal restriction of the elements to print
048   * </ul>
049   * @param key not null
050   * @return string representation
051   */
052  private String getPrintOut(RefBaseObject key) {
053    String result;
054
055    result = elementToPrintOutMap.get( key );
056    if ( result == null ) {
057      result = PRINT_MODEL_ELEMENT.execute( key ).toString();
058      elementToPrintOutMap.put( key, result );
059    }
060    return result;
061  }
062}