Merge "Eliminate XmlUtil.createElement(Document, String)"
[netconf.git] / netconf / mdsal-netconf-connector / src / main / java / org / opendaylight / netconf / mdsal / connector / ops / DiscardChanges.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netconf.mdsal.connector.ops;
9
10 import java.util.HashMap;
11 import java.util.Map;
12 import org.opendaylight.netconf.api.DocumentedException;
13 import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
14 import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
15 import org.opendaylight.netconf.api.DocumentedException.ErrorType;
16 import org.opendaylight.netconf.api.xml.XmlElement;
17 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
18 import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
19 import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22 import org.w3c.dom.Document;
23 import org.w3c.dom.Element;
24
25 public class DiscardChanges extends AbstractSingletonNetconfOperation {
26
27     private static final Logger LOG = LoggerFactory.getLogger(DiscardChanges.class);
28
29     private static final String OPERATION_NAME = "discard-changes";
30
31     private final TransactionProvider transactionProvider;
32
33     public DiscardChanges(final String netconfSessionIdForReporting, final TransactionProvider transactionProvider) {
34         super(netconfSessionIdForReporting);
35         this.transactionProvider = transactionProvider;
36     }
37
38     @Override
39     protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
40             throws DocumentedException {
41
42         try {
43             transactionProvider.abortTransaction();
44         } catch (final IllegalStateException e) {
45             LOG.warn("Abort failed ", e);
46             final Map<String, String> errorInfo = new HashMap<>();
47             errorInfo.put(ErrorTag.OPERATION_FAILED.name(),
48                     "Operation failed. Use 'get-config' or 'edit-config' before triggering "
49                             + OPERATION_NAME + " operation");
50             throw new DocumentedException(e.getMessage(), e, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
51                     ErrorSeverity.ERROR, errorInfo);
52         }
53         return document.createElement(XmlNetconfConstants.OK);
54     }
55
56     @Override
57     protected String getOperationName() {
58         return OPERATION_NAME;
59     }
60
61 }