Adjust to yangtools-2.0.0/odlparent-3.0.0 changes
[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.controller.config.util.xml.DocumentedException;
29 import org.opendaylight.controller.config.util.xml.XmlElement;
30 import org.opendaylight.controller.config.util.xml.XmlUtil;
31 import org.opendaylight.netconf.api.NetconfMessage;
32 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
33 import org.opendaylight.netconf.impl.NetconfServerSession;
34 import org.opendaylight.netconf.impl.mapping.operations.DefaultNetconfOperation;
35 import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
36 import org.w3c.dom.Document;
37 import org.w3c.dom.Element;
38 import org.xml.sax.SAXException;
39
40 public class SimulatedCreateSubscription extends AbstractLastNetconfOperation implements DefaultNetconfOperation {
41
42     private final Map<Notification, NetconfMessage> notifications;
43     private NetconfServerSession session;
44     private ScheduledExecutorService scheduledExecutorService;
45
46     public SimulatedCreateSubscription(final String id, final Optional<File> notificationsFile) {
47         super(id);
48
49         Optional<Notifications> notifs;
50
51         if (notificationsFile.isPresent()) {
52             notifs = Optional.of(loadNotifications(notificationsFile.get()));
53             scheduledExecutorService = Executors.newScheduledThreadPool(1);
54         } else {
55             notifs = Optional.absent();
56         }
57
58         if (notifs.isPresent()) {
59             Map<Notification, NetconfMessage> preparedMessages = Maps.newHashMapWithExpectedSize(
60                 notifs.get().getNotificationList().size());
61             for (final Notification notification : notifs.get().getNotificationList()) {
62                 final NetconfMessage parsedNotification = parseNetconfNotification(notification.getContent());
63                 preparedMessages.put(notification, parsedNotification);
64             }
65             this.notifications = preparedMessages;
66         } else {
67             this.notifications = Collections.emptyMap();
68         }
69
70     }
71
72     private static Notifications loadNotifications(final File file) {
73         try {
74             final JAXBContext jaxbContext = JAXBContext.newInstance(Notifications.class);
75             final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
76             return (Notifications) jaxbUnmarshaller.unmarshal(file);
77         } catch (final JAXBException e) {
78             throw new IllegalArgumentException("Canot parse file " + file + " as a notifications file", e);
79         }
80     }
81
82     @Override
83     protected String getOperationName() {
84         return "create-subscription";
85     }
86
87     @Override
88     protected String getOperationNamespace() {
89         return "urn:ietf:params:xml:ns:netconf:notification:1.0";
90     }
91
92     @Override
93     protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
94             throws DocumentedException {
95         long delayAggregator = 0;
96
97         for (final Map.Entry<Notification, NetconfMessage> notification : notifications.entrySet()) {
98             for (int i = 0; i <= notification.getKey().getTimes(); i++) {
99
100                 delayAggregator += notification.getKey().getDelayInSeconds();
101
102                 scheduledExecutorService.schedule(() -> {
103                     Preconditions.checkState(session != null, "Session is not set, cannot process notifications");
104                     session.sendMessage(notification.getValue());
105                 }, delayAggregator, TimeUnit.SECONDS);
106             }
107         }
108         return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
109     }
110
111     private static NetconfMessage parseNetconfNotification(String content) {
112         final int startEventTime = content.indexOf("<eventTime>") + "<eventTime>".length();
113         final int endEventTime = content.indexOf("</eventTime>");
114         final String eventTime = content.substring(startEventTime, endEventTime);
115         if (eventTime.equals("XXXX")) {
116             content = content.replace(eventTime, new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(new Date()));
117         }
118
119         try {
120             return new NetconfMessage(XmlUtil.readXmlToDocument(content));
121         } catch (SAXException | IOException e) {
122             throw new IllegalArgumentException("Cannot parse notifications", e);
123         }
124     }
125
126     @Override
127     public void setNetconfSession(final NetconfServerSession newSession) {
128         this.session = newSession;
129     }
130
131     @XmlRootElement(name = "notifications")
132     public static final class Notifications {
133
134         @javax.xml.bind.annotation.XmlElement(nillable =  false, name = "notification", required = true)
135         private List<Notification> notificationList;
136
137         public List<Notification> getNotificationList() {
138             return notificationList;
139         }
140
141         @Override
142         public String toString() {
143             final StringBuffer sb = new StringBuffer("Notifications{");
144             sb.append("notificationList=").append(notificationList);
145             sb.append('}');
146             return sb.toString();
147         }
148     }
149
150     public static final class Notification {
151
152         @javax.xml.bind.annotation.XmlElement(nillable = false, name = "delay")
153         private long delayInSeconds;
154
155         @javax.xml.bind.annotation.XmlElement(nillable = false, name = "times")
156         private long times;
157
158         @javax.xml.bind.annotation.XmlElement(nillable = false, name = "content", required = true)
159         private String content;
160
161         public long getDelayInSeconds() {
162             return delayInSeconds;
163         }
164
165         public long getTimes() {
166             return times;
167         }
168
169         public String getContent() {
170             return content;
171         }
172
173         @Override
174         public String toString() {
175             final StringBuffer sb = new StringBuffer("Notification{");
176             sb.append("delayInSeconds=").append(delayInSeconds);
177             sb.append(", times=").append(times);
178             sb.append(", content='").append(content).append('\'');
179             sb.append('}');
180             return sb.toString();
181         }
182     }
183 }