Bug 6995 - Change event notification subscription usability PART2
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / netconf / sal / restconf / impl / RestconfImpl.java
1 /*
2  * Copyright (c) 2014, 2015 Brocade Communication Systems, Inc., 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.sal.restconf.impl;
10
11 import com.google.common.base.CharMatcher;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Splitter;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Lists;
18 import com.google.common.collect.Maps;
19 import com.google.common.collect.Sets;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
23 import java.net.URI;
24 import java.net.URISyntaxException;
25 import java.text.ParseException;
26 import java.text.SimpleDateFormat;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Date;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Set;
37 import java.util.concurrent.CancellationException;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.ExecutionException;
40 import javax.ws.rs.core.Context;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.Response.ResponseBuilder;
43 import javax.ws.rs.core.Response.Status;
44 import javax.ws.rs.core.UriBuilder;
45 import javax.ws.rs.core.UriInfo;
46 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
47 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
48 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
49 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
50 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
52 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
53 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
54 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
55 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
56 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
57 import org.opendaylight.netconf.sal.rest.api.Draft02;
58 import org.opendaylight.netconf.sal.rest.api.RestconfService;
59 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
60 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
61 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
62 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
63 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
64 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
65 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
66 import org.opendaylight.yangtools.yang.common.QName;
67 import org.opendaylight.yangtools.yang.common.QNameModule;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
72 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
75 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
81 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
82 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
83 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
84 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
85 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
86 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
87 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
88 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
89 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
91 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
93 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.Module;
97 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
98 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
99 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
100 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
102 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
103 import org.slf4j.Logger;
104 import org.slf4j.LoggerFactory;
105
106 public class RestconfImpl implements RestconfService {
107
108     private static final RestconfImpl INSTANCE = new RestconfImpl();
109
110     /**
111      * Notifications are served on port 8181.
112      */
113     private static final int NOTIFICATION_PORT = 8181;
114
115     private static final int CHAR_NOT_FOUND = -1;
116
117     private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
118
119     private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
120
121     private BrokerFacade broker;
122
123     private ControllerContext controllerContext;
124
125     private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
126
127     private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
128
129     private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
130
131     private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
132
133     private static final String DATASTORE_PARAM_NAME = "datastore";
134
135     private static final String SCOPE_PARAM_NAME = "scope";
136
137     private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
138
139     private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
140
141     private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
142
143     private static final QName NETCONF_BASE_QNAME;
144
145     private static final QNameModule SAL_REMOTE_AUGMENT;
146
147     private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
148
149     public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
150     private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
151
152     public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
153     private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
154
155     static {
156         try {
157             final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
158             NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null),
159                     NETCONF_BASE_PAYLOAD_NAME);
160             SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
161                     eventSubscriptionAugRevision);
162             SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(
163                     QName.create(SAL_REMOTE_AUGMENT, "scope"),
164                     QName.create(SAL_REMOTE_AUGMENT, "datastore"),
165                     QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
166         } catch (final ParseException e) {
167             final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
168             LOG.debug(errMsg);
169             throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
170         } catch (final URISyntaxException e) {
171             final String errMsg = "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI";
172             throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
173         }
174     }
175
176     public void setBroker(final BrokerFacade broker) {
177         this.broker = broker;
178     }
179
180     public void setControllerContext(final ControllerContext controllerContext) {
181         this.controllerContext = controllerContext;
182     }
183
184     private RestconfImpl() {
185     }
186
187     public static RestconfImpl getInstance() {
188         return INSTANCE;
189     }
190
191     @Override
192     public NormalizedNodeContext getModules(final UriInfo uriInfo) {
193         final Set<Module> allModules = this.controllerContext.getAllModules();
194         final MapNode allModuleMap = makeModuleMapNode(allModules);
195
196         final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
197
198         final Module restconfModule = getRestconfModule();
199         final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
200                 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
201         Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
202
203         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
204                 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
205         moduleContainerBuilder.withChild(allModuleMap);
206
207         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
208                 null, schemaContext), moduleContainerBuilder.build(),
209                 QueryParametersParser.parseWriterParameters(uriInfo));
210     }
211
212     /**
213      * Valid only for mount point
214      */
215     @Override
216     public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
217         Preconditions.checkNotNull(identifier);
218         if ( ! identifier.contains(ControllerContext.MOUNT)) {
219             final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
220                     + " URI has to end with " + ControllerContext.MOUNT;
221             LOG.debug(errMsg + " for " + identifier);
222             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
223         }
224
225         final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext
226                 .toMountPointIdentifier(identifier);
227         final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
228         final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
229         final MapNode mountPointModulesMap = makeModuleMapNode(modules);
230
231         final Module restconfModule = getRestconfModule();
232         final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
233                 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
234         Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
235
236         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
237                 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
238         moduleContainerBuilder.withChild(mountPointModulesMap);
239
240         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
241                 mountPoint, this.controllerContext.getGlobalSchema()), moduleContainerBuilder.build(),
242                 QueryParametersParser.parseWriterParameters(uriInfo));
243     }
244
245     @Override
246     public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
247         Preconditions.checkNotNull(identifier);
248         final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
249         Module module = null;
250         DOMMountPoint mountPoint = null;
251         final SchemaContext schemaContext;
252         if (identifier.contains(ControllerContext.MOUNT)) {
253             final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext
254                     .toMountPointIdentifier(identifier);
255             mountPoint = mountPointIdentifier.getMountPoint();
256             module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
257             schemaContext = mountPoint.getSchemaContext();
258         } else {
259             module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
260             schemaContext = this.controllerContext.getGlobalSchema();
261         }
262
263         if (module == null) {
264             final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
265                     + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
266             LOG.debug(errMsg);
267             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
268         }
269
270         final Module restconfModule = getRestconfModule();
271         final Set<Module> modules = Collections.singleton(module);
272         final MapNode moduleMap = makeModuleMapNode(modules);
273
274         final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
275                 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
276         Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
277
278         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
279                 schemaContext), moduleMap, QueryParametersParser.parseWriterParameters(uriInfo));
280     }
281
282     @Override
283     public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
284         final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
285         final Set<String> availableStreams = Notificator.getStreamNames();
286         final Module restconfModule = getRestconfModule();
287         final DataSchemaNode streamSchemaNode = this.controllerContext
288                 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
289         Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
290
291         final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
292                 .mapBuilder((ListSchemaNode) streamSchemaNode);
293
294         for (final String streamName : availableStreams) {
295             listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
296         }
297
298         final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
299                 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
300         Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
301
302         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
303                 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
304         streamsContainerBuilder.withChild(listStreamsBuilder.build());
305
306
307         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
308                 schemaContext), streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
309     }
310
311     @Override
312     public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
313         final Set<Module> allModules = this.controllerContext.getAllModules();
314         return operationsFromModulesToNormalizedContext(allModules, null);
315     }
316
317     @Override
318     public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
319         Set<Module> modules = null;
320         DOMMountPoint mountPoint = null;
321         if (identifier.contains(ControllerContext.MOUNT)) {
322             final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext
323                     .toMountPointIdentifier(identifier);
324             mountPoint = mountPointIdentifier.getMountPoint();
325             modules = this.controllerContext.getAllModules(mountPoint);
326
327         } else {
328             final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
329                     + "end with ";
330             LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
331             throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
332                     ErrorTag.INVALID_VALUE);
333         }
334
335         return operationsFromModulesToNormalizedContext(modules, mountPoint);
336     }
337
338     /**
339      * Special case only for GET restconf/operations use (since moment of pre-Beryllium
340      * Yang parser and Yang model API removal). The method is creating fake
341      * schema context with fake module and fake data by use own implementations
342      * of schema nodes and module.
343      *
344      * @param modules
345      *            - set of modules for get RPCs from every module
346      * @param mountPoint
347      *            - mount point, if in use otherwise null
348      * @return {@link NormalizedNodeContext}
349      */
350     private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
351             final DOMMountPoint mountPoint) {
352
353         final ContainerSchemaNodeImpl fakeCont = new ContainerSchemaNodeImpl();
354         final List<LeafNode<Object>> listRpcNodes = new ArrayList<>();
355         for (final Module m : modules) {
356             for (final RpcDefinition rpc : m.getRpcs()) {
357
358                 final LeafSchemaNode fakeLeaf = new LeafSchemaNodeImpl(fakeCont.getPath(),
359                         QName.create(ModuleImpl.moduleQName, m.getName() + ":" + rpc.getQName().getLocalName()));
360                 fakeCont.addNodeChild(fakeLeaf);
361                 listRpcNodes.add(Builders.leafBuilder(fakeLeaf).build());
362             }
363         }
364         final ContainerSchemaNode fakeContSchNode = fakeCont;
365         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder = Builders
366                 .containerBuilder(fakeContSchNode);
367
368         for (final LeafNode<Object> rpcNode : listRpcNodes) {
369             containerBuilder.withChild(rpcNode);
370         }
371
372         final Module fakeModule = new ModuleImpl(fakeContSchNode);
373
374         final Set<Module> fakeModules = new HashSet<>();
375         fakeModules.add(fakeModule);
376         final SchemaContext fakeSchemaCtx = EffectiveSchemaContext.resolveSchemaContext(fakeModules);
377         final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
378                 new InstanceIdentifierContext<>(null, fakeContSchNode, mountPoint, fakeSchemaCtx);
379         return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
380     }
381
382     private Module getRestconfModule() {
383         final Module restconfModule = this.controllerContext.getRestconfModule();
384         if (restconfModule == null) {
385             LOG.debug("ietf-restconf module was not found.");
386             throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
387                     ErrorTag.OPERATION_NOT_SUPPORTED);
388         }
389
390         return restconfModule;
391     }
392
393     private static QName getModuleNameAndRevision(final String identifier) {
394         final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
395         String moduleNameAndRevision = "";
396         if (mountIndex >= 0) {
397             moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
398         } else {
399             moduleNameAndRevision = identifier;
400         }
401
402         final Splitter splitter = Splitter.on("/").omitEmptyStrings();
403         final Iterable<String> split = splitter.split(moduleNameAndRevision);
404         final List<String> pathArgs = Lists.<String> newArrayList(split);
405         if (pathArgs.size() < 2) {
406             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
407             throw new RestconfDocumentedException(
408                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
409                     ErrorTag.INVALID_VALUE);
410         }
411
412         try {
413             final String moduleName = pathArgs.get(0);
414             final String revision = pathArgs.get(1);
415             final Date moduleRevision = REVISION_FORMAT.parse(revision);
416             return QName.create(null, moduleRevision, moduleName);
417         } catch (final ParseException e) {
418             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
419             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
420                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
421         }
422     }
423
424     @Override
425     public Object getRoot() {
426         return null;
427     }
428
429     @Override
430     public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
431             final UriInfo uriInfo) {
432         final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
433         final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
434         final CheckedFuture<DOMRpcResult, DOMRpcException> response;
435         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
436         final SchemaContext schemaContext;
437         if (mountPoint != null) {
438             final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
439             if ( ! mountRpcServices.isPresent()) {
440                 LOG.debug("Error: Rpc service is missing.");
441                 throw new RestconfDocumentedException("Rpc service is missing.");
442             }
443             schemaContext = mountPoint.getSchemaContext();
444             response = mountRpcServices.get().invokeRpc(type, payload.getData());
445         } else {
446             if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
447                 if (identifier.contains(CREATE_DATA_SUBSCR)) {
448                     response = invokeSalRemoteRpcSubscribeRPC(payload);
449                 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
450                     response = invokeSalRemoteRpcNotifiStrRPC(payload);
451                 } else {
452                     final String msg = "Not supported operation";
453                     LOG.warn(msg);
454                     throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
455                 }
456             } else {
457                 response = this.broker.invokeRpc(type, payload.getData());
458             }
459             schemaContext = this.controllerContext.getGlobalSchema();
460         }
461
462         final DOMRpcResult result = checkRpcResponse(response);
463
464         RpcDefinition resultNodeSchema = null;
465         final NormalizedNode<?, ?> resultData = result.getResult();
466         if ((result != null) && (result.getResult() != null)) {
467             resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
468         }
469
470         return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
471                 resultNodeSchema, mountPoint, schemaContext), resultData,
472                 QueryParametersParser.parseWriterParameters(uriInfo));
473     }
474
475     private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
476         if (response == null) {
477             return null;
478         }
479         try {
480             final DOMRpcResult retValue = response.get();
481             if ((retValue.getErrors() == null) || retValue.getErrors().isEmpty()) {
482                 return retValue;
483             }
484             LOG.debug("RpcError message", retValue.getErrors());
485             throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
486         } catch (final InterruptedException e) {
487             final String errMsg = "The operation was interrupted while executing and did not complete.";
488             LOG.debug("Rpc Interrupt - " + errMsg, e);
489             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
490         } catch (final ExecutionException e) {
491             LOG.debug("Execution RpcError: ", e);
492             Throwable cause = e.getCause();
493             if (cause != null) {
494                 while (cause.getCause() != null) {
495                     cause = cause.getCause();
496                 }
497
498                 if (cause instanceof IllegalArgumentException) {
499                     throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
500                             ErrorTag.INVALID_VALUE);
501                 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
502                     throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
503                             ErrorTag.OPERATION_NOT_SUPPORTED);
504                 }
505                 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
506                         cause);
507             } else {
508                 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
509                         e);
510             }
511         } catch (final CancellationException e) {
512             final String errMsg = "The operation was cancelled while executing.";
513             LOG.debug("Cancel RpcExecution: " + errMsg, e);
514             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
515         }
516     }
517
518     private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
519         if ((inputSchema != null) && (payload.getData() == null)) {
520             // expected a non null payload
521             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
522         } else if ((inputSchema == null) && (payload.getData() != null)) {
523             // did not expect any input
524             throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
525         }
526     }
527
528     private CheckedFuture<DOMRpcResult, DOMRpcException>
529             invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
530         final ContainerNode value = (ContainerNode) payload.getData();
531         final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
532         final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
533                 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
534         final Object pathValue = path.isPresent() ? path.get().getValue() : null;
535
536         if (!(pathValue instanceof YangInstanceIdentifier)) {
537             final String errMsg = "Instance identifier was not normalized correctly ";
538             LOG.debug(errMsg + rpcQName);
539             throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
540         }
541
542         final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
543         String streamName = (String) CREATE_DATA_SUBSCR;
544         NotificationOutputType outputType = null;
545         if (!pathIdentifier.isEmpty()) {
546             final String fullRestconfIdentifier = DATA_SUBSCR
547                     + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
548
549             LogicalDatastoreType datastore =
550                     parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
551             datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
552
553             DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
554             scope = scope == null ? DEFAULT_SCOPE : scope;
555
556             outputType = parseEnumTypeParameter(value, NotificationOutputType.class,
557                     OUTPUT_TYPE_PARAM_NAME);
558             outputType = outputType == null ? NotificationOutputType.XML : outputType;
559
560             streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
561                     + "/scope=" + scope);
562         }
563
564         if (Strings.isNullOrEmpty(streamName)) {
565             final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
566             LOG.debug(errMsg + pathIdentifier);
567             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
568         }
569
570         final QName outputQname = QName.create(rpcQName, "output");
571         final QName streamNameQname = QName.create(rpcQName, "stream-name");
572
573         final ContainerNode output =
574                 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
575                         .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
576
577         if (!Notificator.existListenerFor(streamName)) {
578             Notificator.createListener(pathIdentifier, streamName, outputType);
579         }
580
581         final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
582
583         return Futures.immediateCheckedFuture(defaultDOMRpcResult);
584     }
585
586     @Override
587     public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
588         if ((noPayload != null) && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
589             throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
590         }
591
592         String identifierEncoded = null;
593         DOMMountPoint mountPoint = null;
594         final SchemaContext schemaContext;
595         if (identifier.contains(ControllerContext.MOUNT)) {
596             // mounted RPC call - look up mount instance.
597             final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
598             mountPoint = mountPointId.getMountPoint();
599             schemaContext = mountPoint.getSchemaContext();
600             final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
601                     + ControllerContext.MOUNT.length() + 1;
602             final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
603             identifierEncoded = remoteRpcName;
604
605         } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
606             final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
607                     + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
608             LOG.debug(slashErrorMsg);
609             throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
610         } else {
611             identifierEncoded = identifier;
612             schemaContext = this.controllerContext.getGlobalSchema();
613         }
614
615         final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
616
617         RpcDefinition rpc = null;
618         if (mountPoint == null) {
619             rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
620         } else {
621             rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
622         }
623
624         if (rpc == null) {
625             LOG.debug("RPC " + identifierDecoded + " does not exist.");
626             throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
627         }
628
629         if (rpc.getInput() != null) {
630             LOG.debug("RPC " + rpc + " does not need input value.");
631             // FIXME : find a correct Error from specification
632             throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
633         }
634
635         final CheckedFuture<DOMRpcResult, DOMRpcException> response;
636         if (mountPoint != null) {
637             final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
638             if ( ! mountRpcServices.isPresent()) {
639                 throw new RestconfDocumentedException("Rpc service is missing.");
640             }
641             response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
642         } else {
643             response = this.broker.invokeRpc(rpc.getPath(), null);
644         }
645
646         final DOMRpcResult result = checkRpcResponse(response);
647
648         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
649                 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
650     }
651
652     private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
653         final String[] splittedIdentifier = identifierDecoded.split(":");
654         if (splittedIdentifier.length != 2) {
655             final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
656             LOG.debug(errMsg);
657             throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
658         }
659         for (final Module module : schemaContext.getModules()) {
660             if (module.getName().equals(splittedIdentifier[0])) {
661                 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
662                     if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
663                         return rpcDefinition;
664                     }
665                 }
666             }
667         }
668         return null;
669     }
670
671     @Override
672     public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
673         final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
674         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
675         NormalizedNode<?, ?> data = null;
676         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
677         if (mountPoint != null) {
678             data = this.broker.readConfigurationData(mountPoint, normalizedII);
679         } else {
680             data = this.broker.readConfigurationData(normalizedII);
681         }
682         if(data == null) {
683             final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
684             LOG.debug(errMsg + identifier);
685             throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
686         }
687         return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
688     }
689
690     @Override
691     public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
692         final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
693         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
694         NormalizedNode<?, ?> data = null;
695         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
696         if (mountPoint != null) {
697             data = this.broker.readOperationalData(mountPoint, normalizedII);
698         } else {
699             data = this.broker.readOperationalData(normalizedII);
700         }
701         if(data == null) {
702             final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
703             LOG.debug(errMsg + identifier);
704             throw new RestconfDocumentedException(errMsg , ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
705         }
706         return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
707     }
708
709     @Override
710     public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
711         Preconditions.checkNotNull(identifier);
712         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
713
714         validateInput(iiWithData.getSchemaNode(), payload);
715         validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
716         validateListKeysEqualityInPayloadAndUri(payload);
717
718         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
719         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
720
721         /*
722          * There is a small window where another write transaction could be updating the same data
723          * simultaneously and we get an OptimisticLockFailedException. This error is likely
724          * transient and The WriteTransaction#submit API docs state that a retry will likely
725          * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
726          * probably will never succeed so we'll fail in that case.
727          *
728          * By retrying we're attempting to hide the internal implementation of the data store and
729          * how it handles concurrent updates from the restconf client. The client has instructed us
730          * to put the data and we should make every effort to do so without pushing optimistic lock
731          * failures back to the client and forcing them to handle it via retry (and having to
732          * document the behavior).
733          */
734         PutResult result = null;
735         final TryOfPutData tryPutData = new TryOfPutData();
736         while(true) {
737             if (mountPoint != null) {
738
739                 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData());
740             } else {
741                 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
742                         payload.getData());
743             }
744             final CountDownLatch waiter = new CountDownLatch(1);
745             Futures.addCallback(result.getFutureOfPutData(), new FutureCallback<Void>() {
746
747                 @Override
748                 public void onSuccess(final Void result) {
749                     handlingLoggerPut(null, tryPutData, identifier);
750                     waiter.countDown();
751                 }
752
753                 @Override
754                 public void onFailure(final Throwable t) {
755                     waiter.countDown();
756                     handlingLoggerPut(t, tryPutData, identifier);
757                 }
758             });
759
760             try {
761                 waiter.await();
762             } catch (final Exception e) {
763                 final String msg = "Problem while waiting for response";
764                 LOG.warn(msg);
765                 throw new RestconfDocumentedException(msg, e);
766             }
767
768             if(tryPutData.isDone()){
769                 break;
770             } else {
771                 throw new RestconfDocumentedException("Problem while PUT operations");
772             }
773         }
774
775         return Response.status(result.getStatus()).build();
776     }
777
778     protected void handlingLoggerPut(final Throwable t, final TryOfPutData tryPutData, final String identifier) {
779         if (t != null) {
780             if (t instanceof OptimisticLockFailedException) {
781                 if (tryPutData.countGet() <= 0) {
782                     LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
783                     throw new RestconfDocumentedException(t.getMessage(), t);
784                 }
785                 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
786                 tryPutData.countDown();
787             } else {
788                 LOG.debug("Update ConfigDataStore fail " + identifier, t);
789                 throw new RestconfDocumentedException(t.getMessage(), t);
790             }
791         } else {
792             LOG.trace("PUT Successful " + identifier);
793             tryPutData.done();
794         }
795     }
796
797     private static void validateTopLevelNodeName(final NormalizedNodeContext node,
798             final YangInstanceIdentifier identifier) {
799
800         final String payloadName = node.getData().getNodeType().getLocalName();
801
802         //no arguments
803         if (identifier.isEmpty()) {
804             //no "data" payload
805             if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
806                 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
807                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
808             }
809         //any arguments
810         } else {
811             final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
812             if (!payloadName.equals(identifierName)) {
813                 throw new RestconfDocumentedException("Payload name (" + payloadName
814                         + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
815                         ErrorTag.MALFORMED_MESSAGE);
816             }
817         }
818     }
819
820     /**
821      * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
822      *
823      * @throws RestconfDocumentedException
824      *             if key values or key count in payload and URI isn't equal
825      *
826      */
827     private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
828         Preconditions.checkArgument(payload != null);
829         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
830         final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
831         final SchemaNode schemaNode = iiWithData.getSchemaNode();
832         final NormalizedNode<?, ?> data = payload.getData();
833         if (schemaNode instanceof ListSchemaNode) {
834             final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
835             if ((lastPathArgument instanceof NodeIdentifierWithPredicates) && (data instanceof MapEntryNode)) {
836                 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
837                 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
838             }
839         }
840     }
841
842     private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
843             final MapEntryNode payload, final List<QName> keyDefinitions) {
844
845         final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
846         for (final QName keyDefinition : keyDefinitions) {
847             final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
848             // should be caught during parsing URI to InstanceIdentifier
849             RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
850                     "Missing key " + keyDefinition + " in URI.");
851
852             final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
853
854             if ( ! uriKeyValue.equals(dataKeyValue)) {
855                 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
856                         "' specified in the URI doesn't match the value '" + dataKeyValue
857                         + "' specified in the message body. ";
858                 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
859             }
860         }
861     }
862
863     @Override
864     public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
865             final UriInfo uriInfo) {
866        return createConfigurationData(payload, uriInfo);
867     }
868
869     // FIXME create RestconfIdetifierHelper and move this method there
870     private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
871         Preconditions.checkArgument(payload != null);
872         Preconditions.checkArgument(payload.getData() != null);
873         Preconditions.checkArgument(payload.getData().getNodeType() != null);
874         Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
875         Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
876
877         final QName payloadNodeQname = payload.getData().getNodeType();
878         final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
879         if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
880             return yangIdent;
881         }
882         final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
883         final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
884         if(parentSchemaNode instanceof DataNodeContainer) {
885             final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
886             for (final DataSchemaNode child : cast.getChildNodes()) {
887                 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
888                     return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
889                 }
890             }
891         }
892         if (parentSchemaNode instanceof RpcDefinition) {
893             return yangIdent;
894         }
895         final String errMsg = "Error parsing input: DataSchemaNode has not children ";
896         LOG.info(errMsg + yangIdent);
897         throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
898     }
899
900     @Override
901     public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
902         if (payload == null) {
903             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
904         }
905
906         // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
907 //        final URI payloadNS = payload.getData().getNodeType().getNamespace();
908 //        if (payloadNS == null) {
909 //            throw new RestconfDocumentedException(
910 //                    "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
911 //                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
912 //        }
913
914         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
915         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
916         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
917
918         CheckedFuture<Void, TransactionCommitFailedException> future;
919         if (mountPoint != null) {
920             future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData());
921         } else {
922             future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
923                     payload.getData());
924         }
925
926         final CountDownLatch waiter = new CountDownLatch(1);
927         Futures.addCallback(future, new FutureCallback<Void>() {
928
929             @Override
930             public void onSuccess(final Void result) {
931                 handlerLoggerPost(null, uriInfo);
932                 waiter.countDown();
933             }
934
935             @Override
936             public void onFailure(final Throwable t) {
937                 waiter.countDown();
938                 handlerLoggerPost(t, uriInfo);
939             }
940         });
941
942         try {
943             waiter.await();
944         } catch (final Exception e) {
945             final String msg = "Problem while waiting for response";
946             LOG.warn(msg);
947             throw new RestconfDocumentedException(msg, e);
948         }
949
950         final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
951         // FIXME: Provide path to result.
952         final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
953         if (location != null) {
954             responseBuilder.location(location);
955         }
956         return responseBuilder.build();
957     }
958
959     protected void handlerLoggerPost(final Throwable t, final UriInfo uriInfo) {
960         if (t != null) {
961             final String errMsg = "Error creating data ";
962             LOG.warn(errMsg + (uriInfo != null ? uriInfo.getPath() : ""), t);
963             throw new RestconfDocumentedException(errMsg, t);
964         } else {
965             LOG.trace("Successfuly create data.");
966         }
967     }
968
969     private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
970             final YangInstanceIdentifier normalizedII) {
971         if(uriInfo == null) {
972             // This is null if invoked internally
973             return null;
974         }
975
976         final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
977         uriBuilder.path("config");
978         try {
979             uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
980         } catch (final Exception e) {
981             LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
982             return null;
983         }
984         return uriBuilder.build();
985     }
986
987     @Override
988     public Response deleteConfigurationData(final String identifier) {
989         final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
990         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
991         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
992
993         final CheckedFuture<Void, TransactionCommitFailedException> future;
994         if (mountPoint != null) {
995             future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
996         } else {
997             future = this.broker.commitConfigurationDataDelete(normalizedII);
998         }
999
1000         final CountDownLatch waiter = new CountDownLatch(1);
1001         Futures.addCallback(future, new FutureCallback<Void>() {
1002
1003             @Override
1004             public void onSuccess(final Void result) {
1005                 handlerLoggerDelete(null);
1006                 waiter.countDown();
1007             }
1008
1009             @Override
1010             public void onFailure(final Throwable t) {
1011                 waiter.countDown();
1012                 handlerLoggerDelete(t);
1013             }
1014
1015         });
1016
1017         try {
1018             waiter.await();
1019         } catch (final Exception e) {
1020             final String msg = "Problem while waiting for response";
1021             LOG.warn(msg);
1022             throw new RestconfDocumentedException(msg, e);
1023         }
1024
1025         return Response.status(Status.OK).build();
1026     }
1027
1028     protected void handlerLoggerDelete(final Throwable t) {
1029         if (t != null) {
1030             final String errMsg = "Error while deleting data";
1031             LOG.info(errMsg, t);
1032             throw new RestconfDocumentedException(errMsg, t);
1033         } else {
1034             LOG.trace("Successfuly delete data.");
1035         }
1036     }
1037
1038     /**
1039      * Subscribes to some path in schema context (stream) to listen on changes on this stream.
1040      *
1041      * Additional parameters for subscribing to stream are loaded via rpc input parameters:
1042      * <ul>
1043      * <li>datastore - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)</li>
1044      * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1045      * </ul>
1046      */
1047     @Override
1048     public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1049         URI response = null;
1050         if (identifier.contains(DATA_SUBSCR)) {
1051             response = dataSubs(identifier, uriInfo);
1052         } else if (identifier.contains(NOTIFICATION_STREAM)) {
1053             response = notifStream(identifier, uriInfo);
1054         }
1055
1056         if(response != null){
1057             // prepare node with value of location
1058             final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1059             final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder = ImmutableLeafNodeBuilder
1060                     .create().withValue(response.toString());
1061             builder.withNodeIdentifier(
1062                     NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1063
1064             // prepare new header with location
1065             final Map<String, Object> headers = new HashMap<>();
1066             headers.put("Location", response);
1067
1068             return new NormalizedNodeContext(iid, builder.build(), headers);
1069         }
1070
1071         final String msg = "Bad type of notification of sal-remote";
1072         LOG.warn(msg);
1073         throw new RestconfDocumentedException(msg);
1074     }
1075
1076     /**
1077      * @return {@link InstanceIdentifierContext} of location leaf for
1078      *         notification
1079      */
1080     private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1081         final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1082         final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1083         final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1084                 .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
1085                 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1086         final List<PathArgument> path = new ArrayList<>();
1087         path.add(NodeIdentifier.create(qnameBase));
1088         path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1089
1090         return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1091                 schemaCtx);
1092     }
1093
1094     /**
1095      * Register notification listener by stream name
1096      *
1097      * @param identifier
1098      *            - stream name
1099      * @param uriInfo
1100      *            - uriInfo
1101      * @return {@link Response}
1102      */
1103     private URI notifStream(final String identifier, final UriInfo uriInfo) {
1104         final String streamName = Notificator.createStreamNameFromUri(identifier);
1105         if (Strings.isNullOrEmpty(streamName)) {
1106             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1107         }
1108         final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1109         if ((listeners == null) || listeners.isEmpty()) {
1110             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1111                     ErrorTag.UNKNOWN_ELEMENT);
1112         }
1113
1114         for (final NotificationListenerAdapter listener : listeners) {
1115             this.broker.registerToListenNotification(listener);
1116         }
1117
1118         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1119         int notificationPort = NOTIFICATION_PORT;
1120         try {
1121             final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1122             notificationPort = webSocketServerInstance.getPort();
1123         } catch (final NullPointerException e) {
1124             WebSocketServer.createInstance(NOTIFICATION_PORT);
1125         }
1126         final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1127         final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1128
1129         return uriToWebsocketServer;
1130     }
1131
1132     /**
1133      * Register data change listener by stream name
1134      *
1135      * @param identifier
1136      *            - stream name
1137      * @param uriInfo
1138      *            - uri info
1139      * @return {@link Response}
1140      */
1141     private URI dataSubs(final String identifier, final UriInfo uriInfo) {
1142         final String streamName = Notificator.createStreamNameFromUri(identifier);
1143         if (Strings.isNullOrEmpty(streamName)) {
1144             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1145         }
1146
1147         final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1148         if (listener == null) {
1149             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1150         }
1151
1152         final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1153         final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1154                 paramToValues.get(DATASTORE_PARAM_NAME));
1155         if (datastore == null) {
1156             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1157                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1158         }
1159         final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1160         if (scope == null) {
1161             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1162                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1163         }
1164
1165         this.broker.registerToListenDataChanges(datastore, scope, listener);
1166
1167         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1168         int notificationPort = NOTIFICATION_PORT;
1169         try {
1170             final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1171             notificationPort = webSocketServerInstance.getPort();
1172         } catch (final NullPointerException e) {
1173             WebSocketServer.createInstance(NOTIFICATION_PORT);
1174         }
1175         final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1176         final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1177
1178         return uriToWebsocketServer;
1179     }
1180
1181     @Override
1182     public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context,
1183             final UriInfo uriInfo) {
1184         if (context == null) {
1185             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1186         }
1187
1188         try {
1189             return this.broker.patchConfigurationDataWithinTransaction(context);
1190         } catch (final Exception e) {
1191             LOG.debug("Patch transaction failed", e);
1192             throw new RestconfDocumentedException(e.getMessage());
1193         }
1194     }
1195
1196     @Override
1197     public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1198         if (context == null) {
1199             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1200         }
1201
1202         try {
1203             return this.broker.patchConfigurationDataWithinTransaction(context);
1204         } catch (final Exception e) {
1205             LOG.debug("Patch transaction failed", e);
1206             throw new RestconfDocumentedException(e.getMessage());
1207         }
1208     }
1209
1210     /**
1211      * Load parameter for subscribing to stream from input composite node
1212      *
1213      * @param value
1214      *            contains value
1215      * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1216      */
1217     private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1218             final String paramName) {
1219         final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1220         if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1221             return null;
1222         }
1223         final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
1224                 ((AugmentationNode) augNode.get())
1225                         .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1226         if (!enumNode.isPresent()) {
1227             return null;
1228         }
1229         final Object rawValue = enumNode.get().getValue();
1230         if (!(rawValue instanceof String)) {
1231             return null;
1232         }
1233
1234         return resolveAsEnum(classDescriptor, (String) rawValue);
1235     }
1236
1237     /**
1238      * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1239      *
1240      * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1241      *         null.
1242      */
1243     private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1244         if (Strings.isNullOrEmpty(value)) {
1245             return null;
1246         }
1247         return resolveAsEnum(classDescriptor, value);
1248     }
1249
1250     private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1251         final T[] enumConstants = classDescriptor.getEnumConstants();
1252         if (enumConstants != null) {
1253             for (final T enm : classDescriptor.getEnumConstants()) {
1254                 if (((Enum<?>) enm).name().equals(value)) {
1255                     return enm;
1256                 }
1257             }
1258         }
1259         return null;
1260     }
1261
1262     private static Map<String, String> resolveValuesFromUri(final String uri) {
1263         final Map<String, String> result = new HashMap<>();
1264         final String[] tokens = uri.split("/");
1265         for (int i = 1; i < tokens.length; i++) {
1266             final String[] parameterTokens = tokens[i].split("=");
1267             if (parameterTokens.length == 2) {
1268                 result.put(parameterTokens[0], parameterTokens[1]);
1269             }
1270         }
1271         return result;
1272     }
1273
1274     private MapNode makeModuleMapNode(final Set<Module> modules) {
1275         Preconditions.checkNotNull(modules);
1276         final Module restconfModule = getRestconfModule();
1277         final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
1278                 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1279         Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1280
1281         final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1282                 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1283
1284         for (final Module module : modules) {
1285             listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1286         }
1287         return listModuleBuilder.build();
1288     }
1289
1290     protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1291         Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1292                 "moduleSchemaNode has to be of type ListSchemaNode");
1293         final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1294         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1295                 .mapEntryBuilder(listModuleSchemaNode);
1296
1297         List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1298                 (listModuleSchemaNode), "name");
1299         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1300         Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1301         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1302                 .build());
1303
1304         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1305                 (listModuleSchemaNode), "revision");
1306         final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1307         Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1308         final String revision = REVISION_FORMAT.format(module.getRevision());
1309         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1310                 .build());
1311
1312         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1313                 (listModuleSchemaNode), "namespace");
1314         final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1315         Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1316         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1317                 .withValue(module.getNamespace().toString()).build());
1318
1319         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1320                 (listModuleSchemaNode), "feature");
1321         final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1322         Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1323         final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1324                 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1325         for (final FeatureDefinition feature : module.getFeatures()) {
1326             featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1327                     .withValue(feature.getQName().getLocalName()).build());
1328         }
1329         moduleNodeValues.withChild(featuresBuilder.build());
1330
1331         return moduleNodeValues.build();
1332     }
1333
1334     protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1335         Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1336                 "streamSchemaNode has to be of type ListSchemaNode");
1337         final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1338         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1339                 .mapEntryBuilder(listStreamSchemaNode);
1340
1341         List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1342                 (listStreamSchemaNode), "name");
1343         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1344         Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1345         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1346                 .build());
1347
1348         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1349                 (listStreamSchemaNode), "description");
1350         final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1351         Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1352         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1353                 .withValue("DESCRIPTION_PLACEHOLDER").build());
1354
1355         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1356                 (listStreamSchemaNode), "replay-support");
1357         final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1358         Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1359         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1360                 .withValue(Boolean.valueOf(true)).build());
1361
1362         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1363                 (listStreamSchemaNode), "replay-log-creation-time");
1364         final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1365         Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1366         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1367                 .withValue("").build());
1368
1369         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1370                 (listStreamSchemaNode), "events");
1371         final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1372         Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1373         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1374                 .withValue("").build());
1375
1376         return streamNodeValues.build();
1377     }
1378
1379     /**
1380      * Prepare stream for notification
1381      *
1382      * @param payload
1383      *            - contains list of qnames of notifications
1384      * @return - checked future object
1385      */
1386     private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1387             final NormalizedNodeContext payload) {
1388         final ContainerNode data = (ContainerNode) payload.getData();
1389         LeafSetNode leafSet = null;
1390         String outputType = "XML";
1391         for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1392             if (dataChild instanceof LeafSetNode) {
1393                 leafSet = (LeafSetNode) dataChild;
1394             } else if (dataChild instanceof AugmentationNode) {
1395                 outputType = (String) (((AugmentationNode) dataChild).getValue()).iterator().next().getValue();
1396             }
1397         }
1398
1399         final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1400         final List<SchemaPath> paths = new ArrayList<>();
1401         String streamName = CREATE_NOTIFICATION_STREAM + "/";
1402
1403         final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1404         while (iterator.hasNext()) {
1405             final QName valueQName = QName.create((String) iterator.next().getValue());
1406             final Module module = ControllerContext.getInstance()
1407                     .findModuleByNamespace(valueQName.getModule().getNamespace());
1408             Preconditions.checkNotNull(module, "Module for namespace " + valueQName.getModule().getNamespace()
1409                     + " does not exist");
1410             NotificationDefinition notifiDef = null;
1411             for (final NotificationDefinition notification : module.getNotifications()) {
1412                 if (notification.getQName().equals(valueQName)) {
1413                     notifiDef = notification;
1414                     break;
1415                 }
1416             }
1417             final String moduleName = module.getName();
1418             Preconditions.checkNotNull(notifiDef,
1419                     "Notification " + valueQName + "doesn't exist in module " + moduleName);
1420             paths.add(notifiDef.getPath());
1421             streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1422             if (iterator.hasNext()) {
1423                 streamName = streamName + ",";
1424             }
1425         }
1426
1427         final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1428         final QName outputQname = QName.create(rpcQName, "output");
1429         final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1430
1431         final ContainerNode output = ImmutableContainerNodeBuilder.create()
1432                 .withNodeIdentifier(new NodeIdentifier(outputQname))
1433                 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1434
1435         if (!Notificator.existNotificationListenerFor(streamName)) {
1436             Notificator.createNotificationListener(paths, streamName, outputType);
1437         }
1438
1439         final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1440
1441         return Futures.immediateCheckedFuture(defaultDOMRpcResult);
1442     }
1443
1444     private class TryOfPutData {
1445         int tries = 2;
1446         boolean done = false;
1447
1448         void countDown() {
1449             this.tries--;
1450         }
1451
1452         void done() {
1453             this.done = true;
1454         }
1455
1456         boolean isDone() {
1457             return this.done;
1458         }
1459         int countGet() {
1460             return this.tries;
1461         }
1462     }
1463 }