Merge "Move ConcurrentDOMDataBroker to clustered-datastore"
[controller.git] / opendaylight / config / config-persister-file-xml-adapter / src / main / java / org / opendaylight / controller / config / persist / storage / file / xml / model / SnapshotHandler.java
1 /*
2  * Copyright (c) 2013 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.controller.config.persist.storage.file.xml.model;
9
10 import com.google.common.base.Preconditions;
11 import java.io.StringReader;
12 import java.io.StringWriter;
13 import javax.xml.bind.ValidationEventHandler;
14 import javax.xml.bind.annotation.DomHandler;
15 import javax.xml.transform.Source;
16 import javax.xml.transform.stream.StreamResult;
17 import javax.xml.transform.stream.StreamSource;
18
19 class SnapshotHandler implements DomHandler<String, StreamResult> {
20
21     private static final String START_TAG = "<configuration>";
22     private static final String END_TAG = "</configuration>";
23
24     private StringWriter xmlWriter = new StringWriter();
25
26     public StreamResult createUnmarshaller(ValidationEventHandler errorHandler) {
27         xmlWriter.getBuffer().setLength(0);
28         return new StreamResult(xmlWriter);
29     }
30
31     public String getElement(StreamResult rt) {
32         String xml = rt.getWriter().toString();
33         int beginIndex = xml.indexOf(START_TAG) + START_TAG.length();
34         int endIndex = xml.indexOf(END_TAG);
35         Preconditions.checkArgument(beginIndex != -1 && endIndex != -1,
36                 "Unknown element present in config snapshot(expected only configuration): %s", xml);
37         return xml.substring(beginIndex, endIndex);
38     }
39
40     public Source marshal(String n, ValidationEventHandler errorHandler) {
41         try {
42             String xml = START_TAG + n.trim() + END_TAG;
43             StringReader xmlReader = new StringReader(xml);
44             return new StreamSource(xmlReader);
45         } catch(Exception e) {
46             throw new RuntimeException(e);
47         }
48     }
49
50 }