blob: 33d485f56856950a97b1a2223a245cdd375bd12d [file] [log] [blame]
Yuta HIGUCHI8e46acf2016-11-03 17:40:40 -07001/*
2 * Copyright 2016-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16package org.onosproject.net.config;
17
18import static org.slf4j.LoggerFactory.getLogger;
19
20import java.io.IOException;
21
22import org.onlab.osgi.DefaultServiceDirectory;
23import org.onlab.osgi.ServiceDirectory;
24import org.onosproject.codec.CodecContext;
25import org.onosproject.codec.CodecService;
26import org.onosproject.codec.JsonCodec;
27import org.slf4j.Logger;
28import com.fasterxml.jackson.databind.ObjectMapper;
29import com.google.common.base.Throwables;
30
31/**
32 * {@link Config} with access to {@link CodecService}.
33 *
34 * @param <S> type of subject
35 */
36public abstract class BaseConfig<S>
37 extends Config<S>
38 implements CodecContext {
39
40 // might need to make it non-final for unit testing
41 private static final ServiceDirectory SERVICES = new DefaultServiceDirectory();
42 private static final Logger log = getLogger(BaseConfig.class);
43
44 @Override
45 public <T> JsonCodec<T> codec(Class<T> entityClass) {
46 return getService(CodecService.class).getCodec(entityClass);
47 }
48
49 @Override
50 public <T> T getService(Class<T> serviceClass) {
51 return SERVICES.get(serviceClass);
52 }
53
54 @Override
55 public ObjectMapper mapper() {
56 return mapper;
57 }
58
59 /**
60 * Decodes the specified entity from JSON using codec
61 * registered to this context.
62 *
63 * @param json JSON String to decode
64 * @param entityClass entity class
65 * @param <T> entity class type
66 * @return decoded entity
67 */
68 protected <T> T decode(String json, Class<T> entityClass) {
69 try {
70 return decode(mapper().readTree(json), entityClass);
71 } catch (IOException e) {
72 log.error("Exception caught.", e);
73 throw Throwables.propagate(e);
74 }
75 }
76
77}