blob: 0098c43154517914500bad70cba71f2be29c70c1 [file] [log] [blame]
Yuta HIGUCHI8e46acf2016-11-03 17:40:40 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2016-present Open Networking Foundation
Yuta HIGUCHI8e46acf2016-11-03 17:40:40 -07003 *
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
Yuta HIGUCHIa255bb42016-11-03 16:04:08 -070040 private static ServiceDirectory services = new DefaultServiceDirectory();
Yuta HIGUCHI8e46acf2016-11-03 17:40:40 -070041 private static final Logger log = getLogger(BaseConfig.class);
42
43 @Override
44 public <T> JsonCodec<T> codec(Class<T> entityClass) {
45 return getService(CodecService.class).getCodec(entityClass);
46 }
47
48 @Override
49 public <T> T getService(Class<T> serviceClass) {
Yuta HIGUCHIa255bb42016-11-03 16:04:08 -070050 return services.get(serviceClass);
Yuta HIGUCHI8e46acf2016-11-03 17:40:40 -070051 }
52
53 @Override
54 public ObjectMapper mapper() {
55 return mapper;
56 }
57
58 /**
59 * Decodes the specified entity from JSON using codec
60 * registered to this context.
61 *
62 * @param json JSON String to decode
63 * @param entityClass entity class
64 * @param <T> entity class type
65 * @return decoded entity
66 */
67 protected <T> T decode(String json, Class<T> entityClass) {
68 try {
69 return decode(mapper().readTree(json), entityClass);
70 } catch (IOException e) {
71 log.error("Exception caught.", e);
72 throw Throwables.propagate(e);
73 }
74 }
75
76}