blob: 86687c51f1a726082cda0cf90b6c99d7f14f8874 [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
Ray Milkey6a51cb92018-03-06 09:03:03 -080018import com.fasterxml.jackson.databind.ObjectMapper;
Yuta HIGUCHI8e46acf2016-11-03 17:40:40 -070019import org.onlab.osgi.DefaultServiceDirectory;
20import org.onlab.osgi.ServiceDirectory;
21import org.onosproject.codec.CodecContext;
22import org.onosproject.codec.CodecService;
23import org.onosproject.codec.JsonCodec;
24import org.slf4j.Logger;
Ray Milkey6a51cb92018-03-06 09:03:03 -080025
26import java.io.IOException;
27
28import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI8e46acf2016-11-03 17:40:40 -070029
30/**
31 * {@link Config} with access to {@link CodecService}.
32 *
33 * @param <S> type of subject
34 */
35public abstract class BaseConfig<S>
36 extends Config<S>
37 implements CodecContext {
38
Yuta HIGUCHIa255bb42016-11-03 16:04:08 -070039 private static ServiceDirectory services = new DefaultServiceDirectory();
Yuta HIGUCHI8e46acf2016-11-03 17:40:40 -070040 private static final Logger log = getLogger(BaseConfig.class);
41
42 @Override
43 public <T> JsonCodec<T> codec(Class<T> entityClass) {
44 return getService(CodecService.class).getCodec(entityClass);
45 }
46
47 @Override
48 public <T> T getService(Class<T> serviceClass) {
Yuta HIGUCHIa255bb42016-11-03 16:04:08 -070049 return services.get(serviceClass);
Yuta HIGUCHI8e46acf2016-11-03 17:40:40 -070050 }
51
52 @Override
53 public ObjectMapper mapper() {
54 return mapper;
55 }
56
57 /**
58 * Decodes the specified entity from JSON using codec
59 * registered to this context.
60 *
61 * @param json JSON String to decode
62 * @param entityClass entity class
63 * @param <T> entity class type
64 * @return decoded entity
65 */
66 protected <T> T decode(String json, Class<T> entityClass) {
67 try {
68 return decode(mapper().readTree(json), entityClass);
69 } catch (IOException e) {
70 log.error("Exception caught.", e);
Ray Milkey6a51cb92018-03-06 09:03:03 -080071 throw new IllegalArgumentException(e);
Yuta HIGUCHI8e46acf2016-11-03 17:40:40 -070072 }
73 }
74
75}