MATSIM
DisallowedNextLinksAttributeConverter.java
Go to the documentation of this file.
1 package org.matsim.utils.objectattributes.attributeconverters;
2 
3 import java.util.List;
4 import java.util.Map;
5 import java.util.Map.Entry;
6 
7 import org.matsim.api.core.v01.Id;
12 
13 import com.fasterxml.jackson.core.JsonProcessingException;
14 import com.fasterxml.jackson.databind.JavaType;
15 import com.fasterxml.jackson.databind.ObjectMapper;
16 import com.fasterxml.jackson.databind.ObjectWriter;
17 import com.fasterxml.jackson.databind.type.CollectionType;
18 import com.fasterxml.jackson.databind.type.TypeFactory;
19 
25 public class DisallowedNextLinksAttributeConverter implements AttributeConverter<DisallowedNextLinks> {
26 
27  private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
28  private static final ObjectWriter OBJECT_WRITER;
29  private static final JavaType LINK_IDS_LIST_MAP_TYPE;
30  static {
31  // register Deserializers & Serializers for Ids
32  OBJECT_MAPPER.registerModule(IdDeSerializationModule.getInstance());
33 
34  // build type & writer
35  TypeFactory typeFactory = TypeFactory.defaultInstance();
36  JavaType linkIdType = typeFactory.constructParametricType(Id.class, Link.class);
37  CollectionType linkIdsType = typeFactory.constructCollectionType(List.class, linkIdType);
38  CollectionType linkIdsListType = typeFactory.constructCollectionType(List.class, linkIdsType);
39  LINK_IDS_LIST_MAP_TYPE = typeFactory.constructMapType(Map.class, typeFactory.constructType(String.class),
40  linkIdsListType);
41  OBJECT_WRITER = OBJECT_MAPPER.writerFor(LINK_IDS_LIST_MAP_TYPE);
42  }
43 
44  @Override
45  public DisallowedNextLinks convert(String value) {
46  Map<String, List<List<Id<Link>>>> linkIdSequencesMap;
47  try {
48  linkIdSequencesMap = OBJECT_MAPPER.readValue(value, LINK_IDS_LIST_MAP_TYPE);
49  } catch (JsonProcessingException e) {
50  throw new RuntimeException(e);
51  }
52 
54  for (Entry<String, List<List<Id<Link>>>> entry : linkIdSequencesMap.entrySet()) {
55  String mode = entry.getKey();
56  for (List<Id<Link>> linkIdList : entry.getValue()) {
57  dnl.addDisallowedLinkSequence(mode, linkIdList);
58  }
59  }
60  return dnl;
61  }
62 
63  @Override
64  public String convertToString(Object o) {
65  if (o instanceof DisallowedNextLinks dnl) {
66  try {
67  return OBJECT_WRITER.writeValueAsString(dnl.getAsMap());
68  } catch (JsonProcessingException e) {
69  throw new RuntimeException(e);
70  }
71  }
72  throw new IllegalArgumentException();
73  }
74 
75 }