View Javadoc
1   /*
2    * Licensed to The Apereo Foundation under one or more contributor license
3    * agreements. See the NOTICE file distributed with this work for additional
4    * information regarding copyright ownership.
5    *
6    *
7    * The Apereo Foundation licenses this file to you under the Educational
8    * Community License, Version 2.0 (the "License"); you may not use this file
9    * except in compliance with the License. You may obtain a copy of the License
10   * at:
11   *
12   *   http://opensource.org/licenses/ecl2.txt
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   *
20   */
21  
22  package org.opencastproject.util;
23  
24  import static org.opencastproject.util.data.functions.Misc.cast;
25  
26  import org.opencastproject.util.data.Function;
27  
28  import java.util.List;
29  import java.util.Map;
30  
31  public final class JsonVal {
32    private final Object val;
33  
34    public JsonVal(Object val) {
35      this.val = val;
36    }
37  
38    public <A> A as(Function<Object, ? extends A> converter) {
39      return converter.apply(val);
40    }
41  
42    public boolean isObj() {
43      return val instanceof Map;
44    }
45  
46    public boolean isArr() {
47      return val instanceof List;
48    }
49  
50    public Object get() {
51      return val;
52    }
53  
54    public static final Function<Object, String> asString = caster(String.class);
55    public static final Function<Object, Integer> asInteger = caster(Integer.class);
56    public static final Function<Object, Long> asLong = caster(Long.class);
57    public static final Function<Object, Float> asFloat = caster(Float.class);
58    public static final Function<Object, Double> asDouble = caster(Double.class);
59    public static final Function<Object, Boolean> asBoolean = caster(Boolean.class);
60    public static final Function<Object, JsonObj> asJsonObj = new Function<Object, JsonObj>() {
61      @Override public JsonObj apply(Object o) {
62        return JsonObj.jsonObj((Map) o);
63      }
64    };
65    public static final Function<Object, JsonArr> asJsonArr = new Function<Object, JsonArr>() {
66      @Override public JsonArr apply(Object o) {
67        return new JsonArr((List) o);
68      }
69    };
70    public static final Function<Object, JsonVal> asJsonVal = new Function<Object, JsonVal>() {
71      @Override public JsonVal apply(Object o) {
72        return new JsonVal(o);
73      }
74    };
75  
76    private static <A> Function<Object, A> caster(final Class<A> ev) {
77      return new Function<Object, A>() {
78        @Override public A apply(Object o) {
79          return cast(o, ev);
80        }
81      };
82    }
83  }