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.api.match.MatchingCriteria; 017import net.mdatools.modelant.core.operation.element.PrintElementRestricted; 018 019/** 020 * Compare model elements by their restricted print representations. 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 OrderByRestrictedPrint implements Order { 029 030 private final PrintElementRestricted PRINT_MODEL_ELEMENT; 031 032 private final Map<RefBaseObject, String> elementToPrintOutMap = new IdentityHashMap<>(); 033 034 035 public OrderByRestrictedPrint(MatchingCriteria criteria) { 036 PRINT_MODEL_ELEMENT = new PrintElementRestricted("", criteria); 037 } 038 039 public int compare(RefBaseObject o1, RefBaseObject o2) { 040 String rep1; 041 String rep2; 042 043 rep1 = getPrintOut( o1 ); 044 rep2 = getPrintOut( o2 ); 045 046 return rep1.compareTo( rep2 ); 047 } 048 049 /** 050 * @param key not null 051 * @return string representation 052 */ 053 private String getPrintOut(RefBaseObject key) { 054 String result; 055 056 result = elementToPrintOutMap.get( key ); 057 if ( result == null ) { 058 result = PRINT_MODEL_ELEMENT.execute( key ).toString(); 059 elementToPrintOutMap.put( key, result ); 060 } 061 return result; 062 } 063}