09fe2efc3e767ac906bc183d63a11e0ae2343ff9
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / serialization / QNameSerializationContextImpl.java
1 /*
2  * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.datastore.node.utils.serialization;
9
10 import java.net.URI;
11 import java.util.ArrayList;
12 import java.util.Date;
13 import java.util.HashMap;
14 import java.util.List;
15 import java.util.Map;
16 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
17
18 /**
19  * Implementation of the QNameSerializationContext interface.
20  *
21  * @author Thomas Pantelis
22  */
23 public class QNameSerializationContextImpl implements QNameSerializationContext {
24
25     private final Map<Object, Integer> codeMap = new HashMap<>();
26     private final List<String> codes = new ArrayList<>();
27
28     public List<String> getCodes() {
29         return codes;
30     }
31
32     @Override public int addNamespace(URI namespace) {
33         int namespaceInt = getCode(namespace);
34
35         if(namespaceInt == -1) {
36             namespaceInt = addCode(namespace, namespace.toString());
37         }
38         return namespaceInt;
39     }
40
41     @Override public int addRevision(Date revision) {
42         if(revision == null){
43             return -1;
44         }
45
46         int revisionInt = getCode(revision);
47         if(revisionInt == -1) {
48             String formattedRevision =
49                 SimpleDateFormatUtil.getRevisionFormat().format(revision);
50             revisionInt = addCode(revision, formattedRevision);
51         }
52         return revisionInt;
53     }
54
55     @Override public int addLocalName(String localName) {
56         int localNameInt = getCode(localName);
57         if(localNameInt == -1) {
58             localNameInt = addCode(localName, localName);
59         }
60         return localNameInt;
61
62     }
63
64     private int addCode(Object code, String codeStr){
65         int count = codes.size();
66         codes.add(codeStr);
67         codeMap.put(code, Integer.valueOf(count));
68         return count;
69     }
70
71     private int getCode(Object code){
72         Integer value = codeMap.get(code);
73         return value == null ? -1 : value.intValue();
74     }
75 }