blob: aae3614a2565993870c88dffa7c48aab6d721476 [file] [log] [blame]
Jovana Vuletafe32db7d2017-05-01 12:18:00 +02001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
Jovana Vuletafe32db7d2017-05-01 12:18:00 +02003 *
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.onosproject.ofagent.rest;
17
18import com.fasterxml.jackson.databind.JsonNode;
19import com.fasterxml.jackson.databind.ObjectMapper;
20import com.fasterxml.jackson.databind.node.ArrayNode;
21import com.fasterxml.jackson.databind.node.ObjectNode;
22import com.google.common.collect.Sets;
23import org.onosproject.codec.CodecContext;
24import org.onosproject.codec.JsonCodec;
25import org.onosproject.incubator.net.virtual.NetworkId;
26import org.onosproject.ofagent.api.OFAgent;
27import org.onosproject.ofagent.api.OFController;
28import org.onosproject.ofagent.impl.DefaultOFAgent;
29
30import java.util.Set;
31
32import static com.google.common.base.Preconditions.checkNotNull;
33import static com.google.common.base.Preconditions.checkState;
34
35/**
36 * OpenFlow agent JSON codec.
37 */
38public final class OFAgentCodec extends JsonCodec<OFAgent> {
39
40 @Override
41 public ObjectNode encode(OFAgent ofAgent, CodecContext context) {
42 checkNotNull(ofAgent, "OFAgent cannot be null");
43
44 ObjectMapper mapper = context.mapper();
45 ObjectNode ofAgentNode = mapper.createObjectNode();
46 ofAgentNode
47 .put("networkId", ofAgent.networkId().toString())
48 .put("state", ofAgent.state().toString());
49
50 ArrayNode controllers = mapper.createArrayNode();
51 ofAgent.controllers().forEach(ofController -> controllers.add((new OFControllerCodec()).encode(ofController,
52 context)));
53 ofAgentNode.set("controllers", controllers);
54
55 return ofAgentNode;
56 }
57
58 public OFAgent decode(ObjectNode json, CodecContext context) {
59 JsonNode networkId = json.get("networkId");
60 checkNotNull(networkId);
61
62 checkNotNull(json.get("controllers"));
63 checkState(json.get("controllers").isArray());
64 Set<OFController> controllers = Sets.newHashSet();
65 json.get("controllers").forEach(jsonController -> controllers.add((new
66 OFControllerCodec()).decode((ObjectNode) jsonController, context)));
67
68 return DefaultOFAgent.builder()
69 .networkId(NetworkId.networkId(networkId.asLong()))
70 .controllers(controllers)
71 .state(OFAgent.State.STOPPED)
72 .build();
73 }
74
75}