8a42baa7a29e6d263ffcc6c15416ff7f93642333
[netconf.git] / netconf / tools / netconf-testtool / src / main / java / org / opendaylight / netconf / test / tool / rpc / SimulatedCreateSubscription.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.netconf.test.tool.rpc;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Maps;
14 import java.io.File;
15 import java.io.IOException;
16 import java.text.SimpleDateFormat;
17 import java.util.Collections;
18 import java.util.Date;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.concurrent.Executors;
22 import java.util.concurrent.ScheduledExecutorService;
23 import java.util.concurrent.TimeUnit;
24 import javax.xml.bind.JAXBContext;
25 import javax.xml.bind.JAXBException;
26 import javax.xml.bind.Unmarshaller;
27 import javax.xml.bind.annotation.XmlRootElement;
28 import org.opendaylight.netconf.api.NetconfMessage;
29 import org.opendaylight.netconf.api.xml.XmlElement;
30 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
31 import org.opendaylight.netconf.api.xml.XmlUtil;
32 import org.opendaylight.netconf.impl.NetconfServerSession;
33 import org.opendaylight.netconf.impl.mapping.operations.DefaultNetconfOperation;
34 import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
35 import org.w3c.dom.Document;
36 import org.w3c.dom.Element;
37 import org.xml.sax.SAXException;
38
39 public class SimulatedCreateSubscription extends AbstractLastNetconfOperation implements DefaultNetconfOperation {
40
41     private final Map<Notification, NetconfMessage> notifications;
42     private NetconfServerSession session;
43     private ScheduledExecutorService scheduledExecutorService;
44
45     public SimulatedCreateSubscription(final String id, final Optional<File> notificationsFile) {
46         super(id);
47
48         Optional<Notifications> notifs;
49
50         if (notificationsFile.isPresent()) {
51             notifs = Optional.of(loadNotifications(notificationsFile.get()));
52             scheduledExecutorService = Executors.newScheduledThreadPool(1);
53         } else {
54             notifs = Optional.absent();
55         }
56
57         if (notifs.isPresent()) {
58             Map<Notification, NetconfMessage> preparedMessages = Maps.newHashMapWithExpectedSize(
59                 notifs.get().getNotificationList().size());
60             for (final Notification notification : notifs.get().getNotificationList()) {
61                 final NetconfMessage parsedNotification = parseNetconfNotification(notification.getContent());
62                 preparedMessages.put(notification, parsedNotification);
63             }
64             this.notifications = preparedMessages;
65         } else {
66             this.notifications = Collections.emptyMap();
67         }
68
69     }
70
71     private static Notifications loadNotifications(final File file) {
72         try {
73             final JAXBContext jaxbContext = JAXBContext.newInstance(Notifications.class);
74             final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
75             return (Notifications) jaxbUnmarshaller.unmarshal(file);
76         } catch (final JAXBException e) {
77             throw new IllegalArgumentException("Canot parse file " + file + " as a notifications file", e);
78         }
79     }
80
81     @Override
82     protected String getOperationName() {
83         return "create-subscription";
84     }
85
86     @Override
87     protected String getOperationNamespace() {
88         return "urn:ietf:params:xml:ns:netconf:notification:1.0";
89     }
90
91     @Override
92     protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) {
93         long delayAggregator = 0;
94
95         for (final Map.Entry<Notification, NetconfMessage> notification : notifications.entrySet()) {
96             for (int i = 0; i <= notification.getKey().getTimes(); i++) {
97
98                 delayAggregator += notification.getKey().getDelayInSeconds();
99
100                 scheduledExecutorService.schedule(() -> {
101                     Preconditions.checkState(session != null, "Session is not set, cannot process notifications");
102                     session.sendMessage(notification.getValue());
103                 }, delayAggregator, TimeUnit.SECONDS);
104             }
105         }
106         return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
107     }
108
109     private static NetconfMessage parseNetconfNotification(String content) {
110         final int startEventTime = content.indexOf("<eventTime>") + "<eventTime>".length();
111         final int endEventTime = content.indexOf("</eventTime>");
112         final String eventTime = content.substring(startEventTime, endEventTime);
113         if (eventTime.equals("XXXX")) {
114             content = content.replace(eventTime, new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(new Date()));
115         }
116
117         try {
118             return new NetconfMessage(XmlUtil.readXmlToDocument(content));
119         } catch (SAXException | IOException e) {
120             throw new IllegalArgumentException("Cannot parse notifications", e);
121         }
122     }
123
124     @Override
125     public void setNetconfSession(final NetconfServerSession newSession) {
126         this.session = newSession;
127     }
128
129     @XmlRootElement(name = "notifications")
130     public static final class Notifications {
131
132         @javax.xml.bind.annotation.XmlElement(nillable =  false, name = "notification", required = true)
133         private List<Notification> notificationList;
134
135         public List<Notification> getNotificationList() {
136             return notificationList;
137         }
138
139         @Override
140         public String toString() {
141             final StringBuffer sb = new StringBuffer("Notifications{");
142             sb.append("notificationList=").append(notificationList);
143             sb.append('}');
144             return sb.toString();
145         }
146     }
147
148     public static final class Notification {
149
150         @javax.xml.bind.annotation.XmlElement(nillable = false, name = "delay")
151         private long delayInSeconds;
152
153         @javax.xml.bind.annotation.XmlElement(nillable = false, name = "times")
154         private long times;
155
156         @javax.xml.bind.annotation.XmlElement(nillable = false, name = "content", required = true)
157         private String content;
158
159         public long getDelayInSeconds() {
160             return delayInSeconds;
161         }
162
163         public long getTimes() {
164             return times;
165         }
166
167         public String getContent() {
168             return content;
169         }
170
171         @Override
172         public String toString() {
173             final StringBuffer sb = new StringBuffer("Notification{");
174             sb.append("delayInSeconds=").append(delayInSeconds);
175             sb.append(", times=").append(times);
176             sb.append(", content='").append(content).append('\'');
177             sb.append('}');
178             return sb.toString();
179         }
180     }
181 }