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 javax.jmi.reflect.RefBaseObject;
011import javax.jmi.reflect.RefObject;
012
013import net.mdatools.modelant.core.api.Order;
014
015/**
016 * This comparator should be used for ordering of model elements alphabetically, ignoring case,
017 * according to the printed value of the specific named field.
018 * If there is no such field (or association) in the model element of at least of one of the two compared 
019 * model objects, then they are considered equal.
020 */
021public class OrderByField implements Order {
022  /**
023   * The field to sort the elements upon
024   */
025  private final String fieldName;
026
027  /**
028   * @param fieldName is the non-null name to sort elements upon
029   */
030  public OrderByField(String fieldName) {
031    if ( fieldName == null ) {
032      throw new IllegalArgumentException("Expected a non-null field name provided");
033    }
034    this.fieldName = fieldName;
035  }
036
037  /**
038   * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
039   */
040  public int compare(RefBaseObject o1, RefBaseObject o2) {
041    int result;
042    String left;
043    String right;
044
045    if ( o1 instanceof RefObject
046         && o2 instanceof RefObject ) {
047      try {
048        left = ""+((RefObject) o1).refGetValue( fieldName );
049        right= ""+((RefObject) o2).refGetValue( fieldName );
050  
051        result = left.trim().compareTo( right.trim() );
052        
053      } catch (Exception ex) { // wrong name 
054        // suppress the exception
055        result=0;
056      }
057    } else {
058      result = 0;
059    }
060    return result;
061  }
062}