summaryrefslogtreecommitdiffstats
path: root/netconf/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/BrokerFacade.java
blob: ca867cb3b60698adb7464157b1b122798ec2d52a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
/*
 * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.netconf.sal.restconf.impl;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION;
import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.OPERATIONAL;

import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.FluentFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.core.Response.Status;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.common.api.ReadFailedException;
import org.opendaylight.mdsal.dom.api.DOMDataBroker;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
import org.opendaylight.mdsal.dom.api.DOMDataTreeReadOperations;
import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
import org.opendaylight.mdsal.dom.api.DOMMountPoint;
import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
import org.opendaylight.mdsal.dom.api.DOMNotificationService;
import org.opendaylight.mdsal.dom.api.DOMRpcResult;
import org.opendaylight.mdsal.dom.api.DOMRpcService;
import org.opendaylight.mdsal.dom.api.DOMSchemaService;
import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.restconf.common.errors.RestconfError;
import org.opendaylight.restconf.common.patch.PatchContext;
import org.opendaylight.restconf.common.patch.PatchEditOperation;
import org.opendaylight.restconf.common.patch.PatchEntity;
import org.opendaylight.restconf.common.patch.PatchStatusContext;
import org.opendaylight.restconf.common.patch.PatchStatusEntity;
import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.common.ErrorTag;
import org.opendaylight.yangtools.yang.common.ErrorType;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders;
import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class BrokerFacade implements Closeable {
    private static final Logger LOG = LoggerFactory.getLogger(BrokerFacade.class);

    private final ThreadLocal<Boolean> isMounted = new ThreadLocal<>();
    private final DOMNotificationService domNotification;
    private final ControllerContext controllerContext;
    private final DOMDataBroker domDataBroker;

    private volatile DOMRpcService rpcService;

    @Inject
    public BrokerFacade(final DOMRpcService rpcService, final DOMDataBroker domDataBroker,
            final DOMNotificationService domNotification, final ControllerContext controllerContext) {
        this.rpcService = requireNonNull(rpcService);
        this.domDataBroker = requireNonNull(domDataBroker);
        this.domNotification = requireNonNull(domNotification);
        this.controllerContext = requireNonNull(controllerContext);
    }

    /**
     * Factory method.
     *
     * @deprecated Just use
     *             {@link #BrokerFacade(DOMRpcService, DOMDataBroker, DOMNotificationService, ControllerContext)}
     *             constructor instead.
     */
    @Deprecated
    public static BrokerFacade newInstance(final DOMRpcService rpcService, final DOMDataBroker domDataBroker,
            final DOMNotificationService domNotification, final ControllerContext controllerContext) {
        return new BrokerFacade(rpcService, domDataBroker, domNotification, controllerContext);
    }

    @Override
    @PreDestroy
    public void close() {
    }

    /**
     * Read config data by path.
     *
     * @param path
     *            path of data
     * @return read date
     */
    public NormalizedNode readConfigurationData(final YangInstanceIdentifier path) {
        return readConfigurationData(path, null);
    }

    /**
     * Read config data by path.
     *
     * @param path
     *            path of data
     * @param withDefa
     *            value of with-defaults parameter
     * @return read date
     */
    public NormalizedNode readConfigurationData(final YangInstanceIdentifier path, final String withDefa) {
        try (DOMDataTreeReadTransaction tx = domDataBroker.newReadOnlyTransaction()) {
            return readDataViaTransaction(tx, CONFIGURATION, path, withDefa);
        }
    }

    /**
     * Read config data from mount point by path.
     *
     * @param mountPoint
     *            mount point for reading data
     * @param path
     *            path of data
     * @return read data
     */
    public NormalizedNode readConfigurationData(final DOMMountPoint mountPoint, final YangInstanceIdentifier path) {
        return readConfigurationData(mountPoint, path, null);
    }

    /**
     * Read config data from mount point by path.
     *
     * @param mountPoint
     *            mount point for reading data
     * @param path
     *            path of data
     * @param withDefa
     *            value of with-defaults parameter
     * @return read data
     */
    public NormalizedNode readConfigurationData(final DOMMountPoint mountPoint, final YangInstanceIdentifier path,
            final String withDefa) {
        final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
        if (domDataBrokerService.isPresent()) {
            try (DOMDataTreeReadTransaction tx = domDataBrokerService.get().newReadOnlyTransaction()) {
                return readDataViaTransaction(tx, CONFIGURATION, path, withDefa);
            }
        }
        throw dataBrokerUnavailable(path);
    }

    /**
     * Read operational data by path.
     *
     * @param path
     *            path of data
     * @return read data
     */
    public NormalizedNode readOperationalData(final YangInstanceIdentifier path) {
        try (DOMDataTreeReadTransaction tx = domDataBroker.newReadOnlyTransaction()) {
            return readDataViaTransaction(tx, OPERATIONAL, path);
        }
    }

    /**
     * Read operational data from mount point by path.
     *
     * @param mountPoint
     *            mount point for reading data
     * @param path
     *            path of data
     * @return read data
     */
    public NormalizedNode readOperationalData(final DOMMountPoint mountPoint, final YangInstanceIdentifier path) {
        final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
        if (domDataBrokerService.isPresent()) {
            try (DOMDataTreeReadTransaction tx = domDataBrokerService.get().newReadOnlyTransaction()) {
                return readDataViaTransaction(tx, OPERATIONAL, path);
            }
        }
        throw dataBrokerUnavailable(path);
    }

    /**
     * <b>PUT configuration data</b>
     *
     * <p>
     * Prepare result(status) for PUT operation and PUT data via transaction.
     * Return wrapped status and future from PUT.
     *
     * @param globalSchema
     *            used by merge parents (if contains list)
     * @param path
     *            path of node
     * @param payload
     *            input data
     * @param point
     *            point
     * @param insert
     *            insert
     * @return wrapper of status and future of PUT
     */
    public PutResult commitConfigurationDataPut(final EffectiveModelContext globalSchema,
            final YangInstanceIdentifier path, final NormalizedNode payload, final String insert, final String point) {
        requireNonNull(globalSchema);
        requireNonNull(path);
        requireNonNull(payload);

        isMounted.set(false);
        final DOMDataTreeReadWriteTransaction newReadWriteTransaction = domDataBroker.newReadWriteTransaction();
        final Status status = readDataViaTransaction(newReadWriteTransaction, CONFIGURATION, path) != null ? Status.OK
                : Status.CREATED;
        final FluentFuture<? extends CommitInfo> future = putDataViaTransaction(
                newReadWriteTransaction, CONFIGURATION, path, payload, globalSchema, insert, point);
        isMounted.remove();
        return new PutResult(status, future);
    }

    /**
     * <b>PUT configuration data (Mount point)</b>
     *
     * <p>
     * Prepare result(status) for PUT operation and PUT data via transaction.
     * Return wrapped status and future from PUT.
     *
     * @param mountPoint
     *            mount point for getting transaction for operation and schema
     *            context for merging parents(if contains list)
     * @param path
     *            path of node
     * @param payload
     *            input data
     * @param point
     *            point
     * @param insert
     *            insert
     * @return wrapper of status and future of PUT
     */
    public PutResult commitMountPointDataPut(final DOMMountPoint mountPoint, final YangInstanceIdentifier path,
            final NormalizedNode payload, final String insert, final String point) {
        requireNonNull(mountPoint);
        requireNonNull(path);
        requireNonNull(payload);

        isMounted.set(true);
        final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
        if (domDataBrokerService.isPresent()) {
            final DOMDataTreeReadWriteTransaction newReadWriteTransaction =
                    domDataBrokerService.get().newReadWriteTransaction();
            final Status status = readDataViaTransaction(newReadWriteTransaction, CONFIGURATION, path) != null
                    ? Status.OK : Status.CREATED;
            final FluentFuture<? extends CommitInfo> future = putDataViaTransaction(
                    newReadWriteTransaction, CONFIGURATION, path, payload, modelContext(mountPoint), insert, point);
            isMounted.remove();
            return new PutResult(status, future);
        }
        isMounted.remove();
        throw dataBrokerUnavailable(path);
    }

    public PatchStatusContext patchConfigurationDataWithinTransaction(final PatchContext patchContext)
            throws Exception {
        final DOMMountPoint mountPoint = patchContext.getInstanceIdentifierContext().getMountPoint();

        // get new transaction and schema context on server or on mounted device
        final EffectiveModelContext schemaContext;
        final DOMDataTreeReadWriteTransaction patchTransaction;
        if (mountPoint == null) {
            schemaContext = patchContext.getInstanceIdentifierContext().getSchemaContext();
            patchTransaction = domDataBroker.newReadWriteTransaction();
        } else {
            schemaContext = modelContext(mountPoint);

            final Optional<DOMDataBroker> optional = mountPoint.getService(DOMDataBroker.class);

            if (optional.isPresent()) {
                patchTransaction = optional.get().newReadWriteTransaction();
            } else {
                // if mount point does not have broker it is not possible to continue and global error is reported
                LOG.error("Http Patch {} has failed - device {} does not support broker service",
                        patchContext.getPatchId(), mountPoint.getIdentifier());
                return new PatchStatusContext(
                        patchContext.getPatchId(),
                        null,
                        false,
                        ImmutableList.of(new RestconfError(ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
                            "DOM data broker service isn't available for mount point " + mountPoint.getIdentifier()))
                );
            }
        }

        final List<PatchStatusEntity> editCollection = new ArrayList<>();
        List<RestconfError> editErrors;
        boolean withoutError = true;

        for (final PatchEntity patchEntity : patchContext.getData()) {
            final PatchEditOperation operation = patchEntity.getOperation();
            switch (operation) {
                case CREATE:
                    if (withoutError) {
                        try {
                            postDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity.getTargetNode(),
                                    patchEntity.getNode(), schemaContext);
                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
                        } catch (final RestconfDocumentedException e) {
                            LOG.error("Error call http Patch operation {} on target {}",
                                    operation,
                                    patchEntity.getTargetNode().toString());

                            editErrors = new ArrayList<>();
                            editErrors.addAll(e.getErrors());
                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), false, editErrors));
                            withoutError = false;
                        }
                    }
                    break;
                case REPLACE:
                    if (withoutError) {
                        try {
                            putDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity
                                    .getTargetNode(), patchEntity.getNode(), schemaContext);
                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
                        } catch (final RestconfDocumentedException e) {
                            LOG.error("Error call http Patch operation {} on target {}",
                                    operation,
                                    patchEntity.getTargetNode().toString());

                            editErrors = new ArrayList<>();
                            editErrors.addAll(e.getErrors());
                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), false, editErrors));
                            withoutError = false;
                        }
                    }
                    break;
                case DELETE:
                case REMOVE:
                    if (withoutError) {
                        try {
                            deleteDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity
                                    .getTargetNode());
                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
                        } catch (final RestconfDocumentedException e) {
                            LOG.error("Error call http Patch operation {} on target {}",
                                    operation,
                                    patchEntity.getTargetNode().toString());

                            editErrors = new ArrayList<>();
                            editErrors.addAll(e.getErrors());
                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), false, editErrors));
                            withoutError = false;
                        }
                    }
                    break;
                case MERGE:
                    if (withoutError) {
                        try {
                            mergeDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity.getTargetNode(),
                                    patchEntity.getNode(), schemaContext);
                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
                        } catch (final RestconfDocumentedException e) {
                            LOG.error("Error call http Patch operation {} on target {}",
                                    operation,
                                    patchEntity.getTargetNode().toString());

                            editErrors = new ArrayList<>();
                            editErrors.addAll(e.getErrors());
                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), false, editErrors));
                            withoutError = false;
                        }
                    }
                    break;
                default:
                    LOG.error("Unsupported http Patch operation {} on target {}",
                            operation,
                            patchEntity.getTargetNode().toString());
                    break;
            }
        }

        // if errors then cancel transaction and return error status
        if (!withoutError) {
            patchTransaction.cancel();
            return new PatchStatusContext(patchContext.getPatchId(), ImmutableList.copyOf(editCollection), false, null);
        }

        // if no errors commit transaction
        final CountDownLatch waiter = new CountDownLatch(1);
        final FluentFuture<? extends CommitInfo> future = patchTransaction.commit();
        final PatchStatusContextHelper status = new PatchStatusContextHelper();

        future.addCallback(new FutureCallback<CommitInfo>() {
            @Override
            public void onSuccess(final CommitInfo result) {
                status.setStatus(new PatchStatusContext(patchContext.getPatchId(), ImmutableList.copyOf(editCollection),
                        true, null));
                waiter.countDown();
            }

            @Override
            public void onFailure(final Throwable throwable) {
                // if commit failed it is global error
                LOG.error("Http Patch {} transaction commit has failed", patchContext.getPatchId());
                status.setStatus(new PatchStatusContext(patchContext.getPatchId(), ImmutableList.copyOf(editCollection),
                    false, ImmutableList.of(
                        new RestconfError(ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, throwable.getMessage()))));
                waiter.countDown();
            }
        }, MoreExecutors.directExecutor());

        waiter.await();
        return status.getStatus();
    }

    // POST configuration
    public FluentFuture<? extends CommitInfo> commitConfigurationDataPost(
            final EffectiveModelContext globalSchema, final YangInstanceIdentifier path,
            final NormalizedNode payload, final String insert, final String point) {
        isMounted.set(false);
        FluentFuture<? extends CommitInfo> future =
                postDataViaTransaction(domDataBroker.newReadWriteTransaction(), CONFIGURATION, path, payload,
                                       globalSchema, insert, point);
        isMounted.remove();
        return future;
    }

    public FluentFuture<? extends CommitInfo> commitConfigurationDataPost(
            final DOMMountPoint mountPoint, final YangInstanceIdentifier path, final NormalizedNode payload,
            final String insert, final String point) {
        isMounted.set(true);
        final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
        if (domDataBrokerService.isPresent()) {
            FluentFuture<? extends CommitInfo> future =
                    postDataViaTransaction(domDataBrokerService.get().newReadWriteTransaction(), CONFIGURATION, path,
                                           payload, modelContext(mountPoint), insert, point);
            isMounted.remove();
            return future;
        }
        isMounted.remove();
        throw dataBrokerUnavailable(path);
    }

    // DELETE configuration
    public FluentFuture<? extends CommitInfo> commitConfigurationDataDelete(final YangInstanceIdentifier path) {
        return deleteDataViaTransaction(domDataBroker.newReadWriteTransaction(), CONFIGURATION, path);
    }

    public FluentFuture<? extends CommitInfo> commitConfigurationDataDelete(
            final DOMMountPoint mountPoint, final YangInstanceIdentifier path) {
        final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
        if (domDataBrokerService.isPresent()) {
            return deleteDataViaTransaction(domDataBrokerService.get().newReadWriteTransaction(), CONFIGURATION, path);
        }
        throw dataBrokerUnavailable(path);
    }

    // RPC
    public ListenableFuture<? extends DOMRpcResult> invokeRpc(final @NonNull QName type,
            final @NonNull NormalizedNode input) {
        if (rpcService == null) {
            throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
        }
        LOG.trace("Invoke RPC {} with input: {}", type, input);
        return rpcService.invokeRpc(type, input);
    }

    public void registerToListenDataChanges(final LogicalDatastoreType datastore, final Scope scope,
            final ListenerAdapter listener) {
        if (listener.isListening()) {
            return;
        }

        final YangInstanceIdentifier path = listener.getPath();
        DOMDataTreeChangeService changeService = domDataBroker.getExtensions()
                .getInstance(DOMDataTreeChangeService.class);
        if (changeService == null) {
            throw new UnsupportedOperationException("DOMDataBroker does not support the DOMDataTreeChangeService"
                                                        + domDataBroker);
        }
        DOMDataTreeIdentifier root = new DOMDataTreeIdentifier(datastore, path);
        ListenerRegistration<ListenerAdapter> registration =
                                    changeService.registerDataTreeChangeListener(root, listener);
        listener.setRegistration(registration);
    }

    private NormalizedNode readDataViaTransaction(final DOMDataTreeReadOperations transaction,
            final LogicalDatastoreType datastore, final YangInstanceIdentifier path) {
        return readDataViaTransaction(transaction, datastore, path, null);
    }

    private NormalizedNode readDataViaTransaction(final DOMDataTreeReadOperations transaction,
            final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final String withDefa) {
        LOG.trace("Read {} via Restconf: {}", datastore.name(), path);

        try {
            final Optional<NormalizedNode> optional = transaction.read(datastore, path).get();
            return optional.map(normalizedNode -> withDefa == null ? normalizedNode :
                prepareDataByParamWithDef(normalizedNode, path, withDefa)).orElse(null);
        } catch (InterruptedException e) {
            LOG.warn("Error reading {} from datastore {}", path, datastore.name(), e);
            throw new RestconfDocumentedException("Error reading data.", e);
        } catch (ExecutionException e) {
            LOG.warn("Error reading {} from datastore {}", path, datastore.name(), e);
            throw RestconfDocumentedException.decodeAndThrow("Error reading data.", Throwables.getCauseAs(e,
                ReadFailedException.class));
        }
    }

    private NormalizedNode prepareDataByParamWithDef(final NormalizedNode result,
            final YangInstanceIdentifier path, final String withDefa) {
        boolean trim;
        switch (withDefa) {
            case "trim":
                trim = true;
                break;
            case "explicit":
                trim = false;
                break;
            default:
                throw new RestconfDocumentedException("Bad value used with with-defaults parameter : " + withDefa);
        }

        final EffectiveModelContext ctx = controllerContext.getGlobalSchema();
        final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
        final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
        if (result instanceof ContainerNode) {
            final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
                SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
            buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
            return builder.build();
        }

        final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
            SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
        buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
            ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
        return builder.build();
    }

    private void buildMapEntryBuilder(
            final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
            final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
            final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
        for (final DataContainerChild child : result.body()) {
            final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
            final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
            if (child instanceof ContainerNode) {
                final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> childBuilder =
                        SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
                buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
                builder.withChild(childBuilder.build());
            } else if (child instanceof MapNode) {
                final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
                        SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
                buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
                        ((ListSchemaNode) childSchema).getKeyDefinition());
                builder.withChild(childBuilder.build());
            } else if (child instanceof LeafNode) {
                final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
                final Object nodeVal = child.body();
                final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
                        SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
                if (keys.contains(child.getIdentifier().getNodeType())) {
                    leafBuilder.withValue(child.body());
                    builder.withChild(leafBuilder.build());
                } else {
                    if (trim) {
                        if (defaultVal == null || !defaultVal.equals(nodeVal)) {
                            leafBuilder.withValue(child.body());
                            builder.withChild(leafBuilder.build());
                        }
                    } else {
                        if (defaultVal != null && defaultVal.equals(nodeVal)) {
                            leafBuilder.withValue(child.body());
                            builder.withChild(leafBuilder.build());
                        }
                    }
                }
            }
        }
    }

    private void buildList(final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder, final MapNode result,
            final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path, final boolean trim,
            final List<QName> keys) {
        for (final MapEntryNode mapEntryNode : result.body()) {
            final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
            final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(actualNode).orElseThrow()
                    .getDataSchemaNode();
            final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
                    SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) childSchema);
            buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
            builder.withChild(mapEntryBuilder.build());
        }
    }

    private void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
            final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
            final YangInstanceIdentifier actualPath, final boolean trim) {
        for (final DataContainerChild child : result.body()) {
            final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
            final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
            if (child instanceof ContainerNode) {
                final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builderChild =
                        SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
                buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
                builder.withChild(builderChild.build());
            } else if (child instanceof MapNode) {
                final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
                        SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
                buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
                        ((ListSchemaNode) childSchema).getKeyDefinition());
                builder.withChild(childBuilder.build());
            } else if (child instanceof LeafNode) {
                final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
                final Object nodeVal = child.body();
                final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
                        SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
                if (trim) {
                    if (defaultVal == null || !defaultVal.equals(nodeVal)) {
                        leafBuilder.withValue(child.body());
                        builder.withChild(leafBuilder.build());
                    }
                } else {
                    if (defaultVal != null && defaultVal.equals(nodeVal)) {
                        leafBuilder.withValue(child.body());
                        builder.withChild(leafBuilder.build());
                    }
                }
            }
        }
    }

    /**
     * POST data and submit transaction {@link DOMDataReadWriteTransaction}.
     */
    private FluentFuture<? extends CommitInfo> postDataViaTransaction(
            final DOMDataTreeReadWriteTransaction rwTransaction, final LogicalDatastoreType datastore,
            final YangInstanceIdentifier path, final NormalizedNode payload,
            final EffectiveModelContext schemaContext, final String insert, final String point) {
        LOG.trace("POST {} via Restconf: {} with payload {}", datastore.name(), path, payload);
        postData(rwTransaction, datastore, path, payload, schemaContext, insert, point);
        return rwTransaction.commit();
    }

    /**
     * POST data and do NOT submit transaction {@link DOMDataReadWriteTransaction}.
     */
    private void postDataWithinTransaction(
            final DOMDataTreeReadWriteTransaction rwTransaction, final LogicalDatastoreType datastore,
            final YangInstanceIdentifier path, final NormalizedNode payload,
            final EffectiveModelContext schemaContext) {
        LOG.trace("POST {} within Restconf Patch: {} with payload {}", datastore.name(), path, payload);
        postData(rwTransaction, datastore, path, payload, schemaContext, null, null);
    }

    private void postData(final DOMDataTreeReadWriteTransaction rwTransaction, final LogicalDatastoreType datastore,
                          final YangInstanceIdentifier path, final NormalizedNode payload,
                          final EffectiveModelContext schemaContext, final String insert, final String point) {
        if (insert == null) {
            makeNormalPost(rwTransaction, datastore, path, payload, schemaContext);
            return;
        }

        final DataSchemaNode schemaNode = checkListAndOrderedType(schemaContext, path);
        checkItemDoesNotExists(rwTransaction, datastore, path);
        switch (insert) {
            case "first":
                if (schemaNode instanceof ListSchemaNode) {
                    final UserMapNode readList =
                            (UserMapNode) this.readConfigurationData(path.getParent().getParent());
                    if (readList == null || readList.isEmpty()) {
                        simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
                    } else {
                        rwTransaction.delete(datastore, path.getParent().getParent());
                        simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
                        makeNormalPost(rwTransaction, datastore, path.getParent().getParent(), readList,
                            schemaContext);
                    }
                } else {
                    final UserLeafSetNode<?> readLeafList =
                            (UserLeafSetNode<?>) readConfigurationData(path.getParent());
                    if (readLeafList == null || readLeafList.isEmpty()) {
                        simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
                    } else {
                        rwTransaction.delete(datastore, path.getParent());
                        simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
                        makeNormalPost(rwTransaction, datastore, path.getParent().getParent(), readLeafList,
                            schemaContext);
                    }
                }
                break;
            case "last":
                simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
                break;
            case "before":
                if (schemaNode instanceof ListSchemaNode) {
                    final UserMapNode readList =
                            (UserMapNode) this.readConfigurationData(path.getParent().getParent());
                    if (readList == null || readList.isEmpty()) {
                        simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
                    } else {
                        insertWithPointListPost(rwTransaction, datastore, path, payload, schemaContext, point,
                            readList,
                            true);
                    }
                } else {
                    final UserLeafSetNode<?> readLeafList =
                            (UserLeafSetNode<?>) readConfigurationData(path.getParent());
                    if (readLeafList == null || readLeafList.isEmpty()) {
                        simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
                    } else {
                        insertWithPointLeafListPost(rwTransaction, datastore, path, payload, schemaContext, point,
                            readLeafList, true);
                    }
                }
                break;
            case "after":
                if (schemaNode instanceof ListSchemaNode) {
                    final UserMapNode readList =
                            (UserMapNode) this.readConfigurationData(path.getParent().getParent());
                    if (readList == null || readList.isEmpty()) {
                        simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
                    } else {
                        insertWithPointListPost(rwTransaction, datastore, path, payload, schemaContext, point,
                            readList,
                            false);
                    }
                } else {
                    final UserLeafSetNode<?> readLeafList =
                            (UserLeafSetNode<?>) readConfigurationData(path.getParent());
                    if (readLeafList == null || readLeafList.isEmpty()) {
                        simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
                    } else {
                        insertWithPointLeafListPost(rwTransaction, datastore, path, payload, schemaContext, point,
                            readLeafList, false);
                    }
                }
                break;
            default:
                throw new RestconfDocumentedException(
                    "Used bad value of insert parameter. Possible values are first, last, before or after, "
                            + "but was: " + insert);
        }
    }

    private void insertWithPointLeafListPost(final DOMDataTreeReadWriteTransaction rwTransaction,
            final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode payload,
            final EffectiveModelContext schemaContext, final String point, final UserLeafSetNode<?> readLeafList,
            final boolean before) {
        rwTransaction.delete(datastore, path.getParent().getParent());
        final InstanceIdentifierContext instanceIdentifier = controllerContext.toInstanceIdentifier(point);
        int lastItemPosition = 0;
        for (final LeafSetEntryNode<?> nodeChild : readLeafList.body()) {
            if (nodeChild.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
                break;
            }
            lastItemPosition++;
        }
        if (!before) {
            lastItemPosition++;
        }
        int lastInsertedPosition = 0;
        final NormalizedNode emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent().getParent());
        rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
        for (final LeafSetEntryNode<?> nodeChild : readLeafList.body()) {
            if (lastInsertedPosition == lastItemPosition) {
                checkItemDoesNotExists(rwTransaction, datastore, path);
                simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
            }
            final YangInstanceIdentifier childPath = path.getParent().getParent().node(nodeChild.getIdentifier());
            checkItemDoesNotExists(rwTransaction, datastore, childPath);
            rwTransaction.put(datastore, childPath, nodeChild);
            lastInsertedPosition++;
        }
    }

    private void insertWithPointListPost(final DOMDataTreeReadWriteTransaction rwTransaction,
            final LogicalDatastoreType datastore,
            final YangInstanceIdentifier path, final NormalizedNode payload, final EffectiveModelContext schemaContext,
            final String point, final MapNode readList, final boolean before) {
        rwTransaction.delete(datastore, path.getParent().getParent());
        final InstanceIdentifierContext instanceIdentifier = controllerContext.toInstanceIdentifier(point);
        int lastItemPosition = 0;
        for (final MapEntryNode mapEntryNode : readList.body()) {
            if (mapEntryNode.getIdentifier()
                    .equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
                break;
            }
            lastItemPosition++;
        }
        if (!before) {
            lastItemPosition++;
        }
        int lastInsertedPosition = 0;
        final NormalizedNode emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent().getParent());
        rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
        for (final MapEntryNode mapEntryNode : readList.body()) {
            if (lastInsertedPosition == lastItemPosition) {
                checkItemDoesNotExists(rwTransaction, datastore, path);
                simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
            }
            final YangInstanceIdentifier childPath = path.getParent().getParent().node(mapEntryNode.getIdentifier());
            checkItemDoesNotExists(rwTransaction, datastore, childPath);
            rwTransaction.put(datastore, childPath, mapEntryNode);
            lastInsertedPosition++;
        }
    }

    private static DataSchemaNode checkListAndOrderedType(final EffectiveModelContext ctx,
            final YangInstanceIdentifier path) {
        final YangInstanceIdentifier parent = path.getParent();
        final DataSchemaContextNode<?> node = DataSchemaContextTree.from(ctx).findChild(parent).orElseThrow();
        final DataSchemaNode dataSchemaNode = node.getDataSchemaNode();

        if (dataSchemaNode instanceof ListSchemaNode) {
            if (!((ListSchemaNode) dataSchemaNode).isUserOrdered()) {
                throw new RestconfDocumentedException("Insert parameter can be used only with ordered-by user list.");
            }
            return dataSchemaNode;
        }
        if (dataSchemaNode instanceof LeafListSchemaNode) {
            if (!((LeafListSchemaNode) dataSchemaNode).isUserOrdered()) {
                throw new RestconfDocumentedException(
                        "Insert parameter can be used only with ordered-by user leaf-list.");
            }
            return dataSchemaNode;
        }
        throw new RestconfDocumentedException("Insert parameter can be used only with list or leaf-list");
    }

    private void makeNormalPost(final DOMDataTreeReadWriteTransaction rwTransaction,
            final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode payload,
            final EffectiveModelContext schemaContext) {
        final Collection<? extends NormalizedNode> children;
        if (payload instanceof MapNode) {
            children = ((MapNode) payload).body();
        } else if (payload instanceof LeafSetNode) {
            children = ((LeafSetNode<?>) payload).body();
        } else {
            simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
            return;
        }

        final NormalizedNode emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
        if (children.isEmpty()) {
            if (isMounted != null && !isMounted.get()) {

                rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()),
                                    emptySubtree);
                ensureParentsByMerge(datastore, path, rwTransaction, schemaContext);
            }
            return;
        }

        // Kick off batch existence check first...
        final BatchedExistenceCheck check = BatchedExistenceCheck.start(rwTransaction, datastore, path, children);

        // ... now enqueue modifications. This relies on proper ordering of requests, i.e. these will not affect the
        // result of the existence checks...
        if (isMounted != null && !isMounted.get()) {

            rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
            ensureParentsByMerge(datastore, path, rwTransaction, schemaContext);
        }
        for (final NormalizedNode child : children) {
            // FIXME: we really want a create(YangInstanceIdentifier, NormalizedNode) method in the transaction,
            //        as that would allow us to skip the existence checks
            rwTransaction.put(datastore, path.node(child.getIdentifier()), child);
        }

        // ... finally collect existence checks and abort the transaction if any of them failed.
        final Entry<YangInstanceIdentifier, ReadFailedException> failure;
        try {
            failure = check.getFailure();
        } catch (InterruptedException e) {
            rwTransaction.cancel();
            throw new RestconfDocumentedException("Could not determine the existence of path " + path, e);
        }

        if (failure != null) {
            rwTransaction.cancel();
            final ReadFailedException e = failure.getValue();
            if (e == null) {
                throw new RestconfDocumentedException("Data already exists for path: " + failure.getKey(),
                    ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS);
            }

            throw new RestconfDocumentedException("Could not determine the existence of path " + failure.getKey(), e,
                e.getErrorList());
        }
    }

    private void simplePostPut(final DOMDataTreeReadWriteTransaction rwTransaction,
            final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode payload,
            final EffectiveModelContext schemaContext) {
        checkItemDoesNotExists(rwTransaction, datastore, path);
        if (isMounted != null && !isMounted.get()) {
            ensureParentsByMerge(datastore, path, rwTransaction, schemaContext);
        }
        rwTransaction.put(datastore, path, payload);
    }

    private static boolean doesItemExist(final DOMDataTreeReadWriteTransaction rwTransaction,
            final LogicalDatastoreType store, final YangInstanceIdentifier path) {
        try {
            return rwTransaction.exists(store, path).get();
        } catch (InterruptedException e) {
            rwTransaction.cancel();
            throw new RestconfDocumentedException("Could not determine the existence of path " + path, e);
        } catch (ExecutionException e) {
            rwTransaction.cancel();
            throw RestconfDocumentedException.decodeAndThrow("Could not determine the existence of path " + path,
                Throwables.getCauseAs(e, ReadFailedException.class));
        }
    }

    /**
     * Check if item already exists. Throws error if it does NOT already exist.
     * @param rwTransaction Current transaction
     * @param store Used datastore
     * @param path Path to item to verify its existence
     */
    private static void checkItemExists(final DOMDataTreeReadWriteTransaction rwTransaction,
            final LogicalDatastoreType store, final YangInstanceIdentifier path) {
        if (!doesItemExist(rwTransaction, store, path)) {
            LOG.trace("Operation via Restconf was not executed because data at {} does not exist", path);
            rwTransaction.cancel();
            throw new RestconfDocumentedException("Data does not exist for path: " + path, ErrorType.PROTOCOL,
                    ErrorTag.DATA_MISSING);
        }
    }

    /**
     * Check if item does NOT already exist. Throws error if it already exists.
     * @param rwTransaction Current transaction
     * @param store Used datastore
     * @param path Path to item to verify its existence
     */
    private static void checkItemDoesNotExists(final DOMDataTreeReadWriteTransaction rwTransaction,
            final LogicalDatastoreType store, final YangInstanceIdentifier path) {
        if (doesItemExist(rwTransaction, store, path)) {
            LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
            rwTransaction.cancel();
            throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL,
                    ErrorTag.DATA_EXISTS);
        }
    }

    /**
     * PUT data and submit {@link DOMDataReadWriteTransaction}.
     *
     * @param point
     *            point
     * @param insert
     *            insert
     */
    private FluentFuture<? extends CommitInfo> putDataViaTransaction(
            final DOMDataTreeReadWriteTransaction readWriteTransaction, final LogicalDatastoreType datastore,
            final YangInstanceIdentifier path, final NormalizedNode payload,
            final EffectiveModelContext schemaContext, final String insert, final String point) {
        LOG.trace("Put {} via Restconf: {} with payload {}", datastore.name(), path, payload);
        putData(readWriteTransaction, datastore, path, payload, schemaContext, insert, point);
        return readWriteTransaction.commit();
    }

    /**
     * PUT data and do NOT submit {@link DOMDataReadWriteTransaction}.
     */
    private void putDataWithinTransaction(
            final DOMDataTreeReadWriteTransaction writeTransaction, final LogicalDatastoreType datastore,
            final YangInstanceIdentifier path, final NormalizedNode payload,
            final EffectiveModelContext schemaContext) {
        LOG.trace("Put {} within Restconf Patch: {} with payload {}", datastore.name(), path, payload);
        putData(writeTransaction, datastore, path, payload, schemaContext, null, null);
    }

    // FIXME: This is doing correct put for container and list children, not sure if this will work for choice case
    private void putData(final DOMDataTreeReadWriteTransaction rwTransaction, final LogicalDatastoreType datastore,
            final YangInstanceIdentifier path, final NormalizedNode payload,
            final EffectiveModelContext schemaContext, final String insert, final String point) {
        if (insert == null) {
            makePut(rwTransaction, datastore, path, payload, schemaContext);
            return;
        }

        final DataSchemaNode schemaNode = checkListAndOrderedType(schemaContext, path);
        checkItemDoesNotExists(rwTransaction, datastore, path);
        switch (insert) {
            case "first":
                if (schemaNode instanceof ListSchemaNode) {
                    final UserMapNode readList = (UserMapNode) this.readConfigurationData(path.getParent());
                    if (readList == null || readList.isEmpty()) {
                        simplePut(datastore, path, rwTransaction, schemaContext, payload);
                    } else {
                        rwTransaction.delete(datastore, path.getParent());
                        simplePut(datastore, path, rwTransaction, schemaContext, payload);
                        makePut(rwTransaction, datastore, path.getParent(), readList, schemaContext);
                    }
                } else {
                    final UserLeafSetNode<?> readLeafList =
                            (UserLeafSetNode<?>) readConfigurationData(path.getParent());
                    if (readLeafList == null || readLeafList.isEmpty()) {
                        simplePut(datastore, path, rwTransaction, schemaContext, payload);
                    } else {
                        rwTransaction.delete(datastore, path.getParent());
                        simplePut(datastore, path, rwTransaction, schemaContext, payload);
                        makePut(rwTransaction, datastore, path.getParent(), readLeafList,
                            schemaContext);
                    }
                }
                break;
            case "last":
                simplePut(datastore, path, rwTransaction, schemaContext, payload);
                break;
            case "before":
                if (schemaNode instanceof ListSchemaNode) {
                    final UserMapNode readList = (UserMapNode) this.readConfigurationData(path.getParent());
                    if (readList == null || readList.isEmpty()) {
                        simplePut(datastore, path, rwTransaction, schemaContext, payload);
                    } else {
                        insertWithPointListPut(rwTransaction, datastore, path, payload, schemaContext, point,
                            readList, true);
                    }
                } else {
                    final UserLeafSetNode<?> readLeafList =
                            (UserLeafSetNode<?>) readConfigurationData(path.getParent());
                    if (readLeafList == null || readLeafList.isEmpty()) {
                        simplePut(datastore, path, rwTransaction, schemaContext, payload);
                    } else {
                        insertWithPointLeafListPut(rwTransaction, datastore, path, payload, schemaContext, point,
                            readLeafList, true);
                    }
                }
                break;
            case "after":
                if (schemaNode instanceof ListSchemaNode) {
                    final UserMapNode readList = (UserMapNode) this.readConfigurationData(path.getParent());
                    if (readList == null || readList.isEmpty()) {
                        simplePut(datastore, path, rwTransaction, schemaContext, payload);
                    } else {
                        insertWithPointListPut(rwTransaction, datastore, path, payload, schemaContext, point,
                            readList, false);
                    }
                } else {
                    final UserLeafSetNode<?> readLeafList =
                            (UserLeafSetNode<?>) readConfigurationData(path.getParent());
                    if (readLeafList == null || readLeafList.isEmpty()) {
                        simplePut(datastore, path, rwTransaction, schemaContext, payload);
                    } else {
                        insertWithPointLeafListPut(rwTransaction, datastore, path, payload, schemaContext, point,
                            readLeafList, false);
                    }
                }
                break;
            default:
                throw new RestconfDocumentedException(
                    "Used bad value of insert parameter. Possible values are first, last, before or after, but was: "
                            + insert);
        }
    }

    private void insertWithPointLeafListPut(final DOMDataTreeWriteTransaction tx,
            final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode payload,
            final EffectiveModelContext schemaContext, final String point, final UserLeafSetNode<?> readLeafList,
            final boolean before) {
        tx.delete(datastore, path.getParent());
        final InstanceIdentifierContext instanceIdentifier = controllerContext.toInstanceIdentifier(point);
        int index1 = 0;
        for (final LeafSetEntryNode<?> nodeChild : readLeafList.body()) {
            if (nodeChild.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
                break;
            }
            index1++;
        }
        if (!before) {
            index1++;
        }
        int index2 = 0;
        final NormalizedNode emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
        tx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
        for (final LeafSetEntryNode<?> nodeChild : readLeafList.body()) {
            if (index2 == index1) {
                simplePut(datastore, path, tx, schemaContext, payload);
            }
            final YangInstanceIdentifier childPath = path.getParent().node(nodeChild.getIdentifier());
            tx.put(datastore, childPath, nodeChild);
            index2++;
        }
    }

    private void insertWithPointListPut(final DOMDataTreeWriteTransaction tx, final LogicalDatastoreType datastore,
            final YangInstanceIdentifier path, final NormalizedNode payload, final EffectiveModelContext schemaContext,
            final String point, final UserMapNode readList, final boolean before) {
        tx.delete(datastore, path.getParent());
        final InstanceIdentifierContext instanceIdentifier = controllerContext.toInstanceIdentifier(point);
        int index1 = 0;
        for (final MapEntryNode mapEntryNode : readList.body()) {
            if (mapEntryNode.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
                break;
            }
            index1++;
        }
        if (!before) {
            index1++;
        }
        int index2 = 0;
        final NormalizedNode emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
        tx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
        for (final MapEntryNode mapEntryNode : readList.body()) {
            if (index2 == index1) {
                simplePut(datastore, path, tx, schemaContext, payload);
            }
            final YangInstanceIdentifier childPath = path.getParent().node(mapEntryNode.getIdentifier());
            tx.put(datastore, childPath, mapEntryNode);
            index2++;
        }
    }

    private void makePut(final DOMDataTreeWriteTransaction tx, final LogicalDatastoreType datastore,
            final YangInstanceIdentifier path, final NormalizedNode payload,
            final EffectiveModelContext schemaContext) {
        if (payload instanceof MapNode) {
            final NormalizedNode emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
            if (isMounted != null && !isMounted.get()) {
                tx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
                ensureParentsByMerge(datastore, path, tx, schemaContext);
            }
            for (final MapEntryNode child : ((MapNode) payload).body()) {
                final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
                tx.put(datastore, childPath, child);
            }
        } else {
            simplePut(datastore, path, tx, schemaContext, payload);
        }
    }

    private void simplePut(final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
            final DOMDataTreeWriteTransaction tx, final EffectiveModelContext schemaContext,
            final NormalizedNode payload) {
        if (isMounted != null && !isMounted.get()) {
            ensureParentsByMerge(datastore, path, tx, schemaContext);
        }
        tx.put(datastore, path, payload);
    }

    private static FluentFuture<? extends CommitInfo> deleteDataViaTransaction(
            final DOMDataTreeReadWriteTransaction readWriteTransaction, final LogicalDatastoreType datastore,
            final YangInstanceIdentifier path) {
        LOG.trace("Delete {} via Restconf: {}", datastore.name(), path);
        checkItemExists(readWriteTransaction, datastore, path);
        readWriteTransaction.delete(datastore, path);
        return readWriteTransaction.commit();
    }

    private static void deleteDataWithinTransaction(final DOMDataTreeWriteTransaction tx,
            final LogicalDatastoreType datastore, final YangInstanceIdentifier path) {
        LOG.trace("Delete {} within Restconf Patch: {}", datastore.name(), path);
        tx.delete(datastore, path);
    }

    private static void mergeDataWithinTransaction(final DOMDataTreeWriteTransaction tx,
            final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode payload,
            final EffectiveModelContext schemaContext) {
        LOG.trace("Merge {} within Restconf Patch: {} with payload {}", datastore.name(), path, payload);
        ensureParentsByMerge(datastore, path, tx, schemaContext);

        // Since YANG Patch provides the option to specify what kind of operation for each edit,
        // OpenDaylight should not change it.
        tx.merge(datastore, path, payload);
    }

    public void registerToListenNotification(final NotificationListenerAdapter listener) {
        if (listener.isListening()) {
            return;
        }

        final ListenerRegistration<DOMNotificationListener> registration = domNotification
                .registerNotificationListener(listener, listener.getSchemaPath());

        listener.setRegistration(registration);
    }

    private static void ensureParentsByMerge(final LogicalDatastoreType store,
            final YangInstanceIdentifier normalizedPath, final DOMDataTreeWriteTransaction tx,
            final EffectiveModelContext schemaContext) {
        final List<PathArgument> normalizedPathWithoutChildArgs = new ArrayList<>();
        YangInstanceIdentifier rootNormalizedPath = null;

        final Iterator<PathArgument> it = normalizedPath.getPathArguments().iterator();

        while (it.hasNext()) {
            final PathArgument pathArgument = it.next();
            if (rootNormalizedPath == null) {
                rootNormalizedPath = YangInstanceIdentifier.create(pathArgument);
            }

            if (it.hasNext()) {
                normalizedPathWithoutChildArgs.add(pathArgument);
            }
        }

        if (normalizedPathWithoutChildArgs.isEmpty()) {
            return;
        }

        checkArgument(rootNormalizedPath != null, "Empty path received");
        tx.merge(store, rootNormalizedPath, ImmutableNodes.fromInstanceId(schemaContext,
            YangInstanceIdentifier.create(normalizedPathWithoutChildArgs)));
    }

    private static RestconfDocumentedException dataBrokerUnavailable(final YangInstanceIdentifier path) {
        LOG.warn("DOM data broker service is not available for mount point {}", path);
        return new RestconfDocumentedException("DOM data broker service is not available for mount point " + path);
    }

    private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
        return mountPoint.getService(DOMSchemaService.class)
            .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
            .orElse(null);
    }

    private static final class PatchStatusContextHelper {
        PatchStatusContext status;

        public PatchStatusContext getStatus() {
            return status;
        }

        public void setStatus(final PatchStatusContext status) {
            this.status = status;
        }
    }
}