blob: ff53182542cf8b425683584438ae0cee1340ece2 [file] [log] [blame]
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -08001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 Open Networking Laboratory
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of 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,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.rest;
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -080017
18import com.fasterxml.jackson.databind.ObjectMapper;
19import com.fasterxml.jackson.databind.node.ObjectNode;
Thomas Vachuskaf8cac482015-04-08 19:40:12 -070020import org.onlab.rest.BaseResource;
Brian O'Connorabafb502014-12-02 22:26:20 -080021import org.onosproject.codec.CodecContext;
22import org.onosproject.codec.CodecService;
23import org.onosproject.codec.JsonCodec;
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -080024
25/**
26 * Abstract REST resource.
27 */
28public class AbstractWebResource extends BaseResource implements CodecContext {
29
30 @Override
31 public ObjectMapper mapper() {
32 return new ObjectMapper();
33 }
34
35 /**
36 * Returns the JSON codec for the specified entity class.
37 *
38 * @param entityClass entity class
39 * @param <T> entity type
40 * @return JSON codec
41 */
42 public <T> JsonCodec<T> codec(Class<T> entityClass) {
43 return get(CodecService.class).getCodec(entityClass);
44 }
45
46 /**
47 * Returns JSON object wrapping the array encoding of the specified
48 * collection of items.
49 *
50 * @param codecClass codec item class
51 * @param field field holding the array
52 * @param items collection of items to be encoded into array
53 * @param <T> item type
54 * @return JSON object
55 */
56 protected <T> ObjectNode encodeArray(Class<T> codecClass, String field,
57 Iterable<T> items) {
58 ObjectNode result = mapper().createObjectNode();
59 result.set(field, codec(codecClass).encode(items, this));
60 return result;
61 }
62
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -080063}