Package urban.transformers

Source Code of urban.transformers.CanonicalBindingsTransformer

package urban.transformers;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections15.Transformer;

import urban.model.Agent;
import urban.model.Site;

/**
* This tries to make sure that the binding marks withing an agent list will not interfere when
* doing comparisons.
*
* @author fwb
*
*/
public class CanonicalBindingsTransformer implements Transformer<Collection<Agent>, Collection<Agent>>{

  @Override
  public Collection<Agent> transform(Collection<Agent> list) {
    if (list == null)
      return null;
    Agent agent = findAgentWithMostSites(list);
   
    Set<String> bindings = new HashSet<String>();
   
    for(Agent a : list){
      if (a != null){
        for (Site s : a.getSites()){
          String x = s.getBindingMark();
          if (x != null && Character.isDigit(x.charAt(0)))
            bindings.add(x);
        }
      }
    }
   
    if (bindings.size() < 1)
      return list;
   
    HashMap<String,String> mapping = new HashMap<String,String>();
   
    int i=1;
    for(Site s : agent.getSites()){
      String x = s.getBindingMark();
      if (x != null && Character.isDigit(x.charAt(0))){
        mapping.put(x, ""+i++);
        bindings.remove(x);
      }
    }
    for(String x : bindings){
      mapping.put(x, ""+i++);
    }
   
    List<Agent> result = new ArrayList<Agent>();
   
    for(Agent a : list){
      List<Site> sites = new ArrayList<Site>();
      for (Site s : a.getSites()){
        String x = s.getBindingMark();
        if (x != null && Character.isDigit(x.charAt(0))){
          sites.add(s.clone().setBindingMark(mapping.get(x)));
        } else {
          sites.add(s);
        }
      }
      result.add(new Agent(a.getName(),sites));
    }
   
    return result;
  }

  private Agent findAgentWithMostSites(Collection<Agent> list) {
    if (list == null)
      return null;
    int maxS =0;
    Agent maxA = null;
   
    for(Agent a : list){
      if (a != null && a.getSites() != null && a.getSites().size() > maxS){
        maxA = a;
        maxS = a.getSites().size();
      }
    }
    return maxA;
  }
}
TOP

Related Classes of urban.transformers.CanonicalBindingsTransformer

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.