View Javadoc
1   /*
2    * Copyright (C) 2013 4th Line GmbH, Switzerland
3    *
4    * The contents of this file are subject to the terms of either the GNU
5    * Lesser General Public License Version 2 or later ("LGPL") or the
6    * Common Development and Distribution License Version 1 or later
7    * ("CDDL") (collectively, the "License"). You may not use this file
8    * except in compliance with the License. See LICENSE.txt for more
9    * information.
10   *
11   * This program is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14   */
15  
16  package org.fourthline.cling.support.lastchange;
17  
18  import org.fourthline.cling.model.types.Datatype;
19  import org.fourthline.cling.model.types.InvalidValueException;
20  import org.fourthline.cling.support.shared.AbstractMap;
21  
22  import java.util.Map;
23  
24  public abstract class EventedValue<V> {
25  
26      final protected V value;
27  
28      public EventedValue(V value) {
29          this.value = value;
30      }
31  
32      public EventedValue(Map.Entry<String,String>[] attributes) {
33          try {
34              this.value = valueOf(attributes);
35          } catch (InvalidValueException ex) {
36              throw new RuntimeException(ex);
37          }
38      }
39  
40      public String getName() {
41          return getClass().getSimpleName();
42      }
43  
44      public V getValue() {
45          return value;
46      }
47  
48      public Map.Entry<String, String>[] getAttributes() {
49          return new Map.Entry[] {
50              new AbstractMap.SimpleEntry<>("val", toString())
51          };
52      }
53  
54      protected V valueOf(Map.Entry<String,String>[] attributes) throws InvalidValueException {
55          V v = null;
56          for (Map.Entry<String, String> attribute : attributes) {
57              if (attribute.getKey().equals("val")) v = valueOf(attribute.getValue());
58          }
59          return v;
60      }
61  
62      protected V valueOf(String s) throws InvalidValueException {
63          return (V)getDatatype().valueOf(s);
64      }
65  
66      @Override
67      public String toString() {
68          return getDatatype().getString(getValue());
69      }
70  
71      abstract protected Datatype getDatatype();
72  }