blob: b36bb1bcef92956d1c8755229768a357b3a3efb6 [file] [log] [blame]
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -08001/*
2 * Copyright 2014 Open Networking Laboratory
3 *
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 */
16package org.onlab.onos.rest;
17
18import com.fasterxml.jackson.databind.ObjectMapper;
19import com.fasterxml.jackson.databind.node.ObjectNode;
Thomas Vachuska21e03642014-11-11 10:23:02 -080020import org.onlab.util.ItemNotFoundException;
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -080021import org.onlab.onos.codec.CodecContext;
22import org.onlab.onos.codec.CodecService;
23import org.onlab.onos.codec.JsonCodec;
24import org.onlab.rest.BaseResource;
25
26/**
27 * Abstract REST resource.
28 */
29public class AbstractWebResource extends BaseResource implements CodecContext {
30
31 @Override
32 public ObjectMapper mapper() {
33 return new ObjectMapper();
34 }
35
36 /**
37 * Returns the JSON codec for the specified entity class.
38 *
39 * @param entityClass entity class
40 * @param <T> entity type
41 * @return JSON codec
42 */
43 public <T> JsonCodec<T> codec(Class<T> entityClass) {
44 return get(CodecService.class).getCodec(entityClass);
45 }
46
47 /**
48 * Returns JSON object wrapping the array encoding of the specified
49 * collection of items.
50 *
51 * @param codecClass codec item class
52 * @param field field holding the array
53 * @param items collection of items to be encoded into array
54 * @param <T> item type
55 * @return JSON object
56 */
57 protected <T> ObjectNode encodeArray(Class<T> codecClass, String field,
58 Iterable<T> items) {
59 ObjectNode result = mapper().createObjectNode();
60 result.set(field, codec(codecClass).encode(items, this));
61 return result;
62 }
63
64 /**
65 * Returns the specified item if that items is null; otherwise throws
66 * not found exception.
67 *
68 * @param item item to check
69 * @param message not found message
70 * @param <T> item type
71 * @return item if not null
Thomas Vachuska21e03642014-11-11 10:23:02 -080072 * @throws org.onlab.util.ItemNotFoundException if item is null
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -080073 */
74 protected <T> T nullIsNotFound(T item, String message) {
75 if (item == null) {
76 throw new ItemNotFoundException(message);
77 }
78 return item;
79 }
80
81}