35b5e55230eadb85c4904ba667f88b7be0bde7ce
[neutron.git] / neutron-spi / src / test / java / org / opendaylight / neutron / spi / JaxbTestHelper.java
1 /*
2  * Copyright (C) 2015 IBM, Inc.
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.neutron.spi;
10
11 import java.io.StringReader;
12 import java.util.HashMap;
13 import java.util.Map;
14 import javax.xml.bind.JAXBContext;
15 import javax.xml.bind.JAXBException;
16 import javax.xml.bind.Unmarshaller;
17 import javax.xml.transform.stream.StreamSource;
18 import org.eclipse.persistence.jaxb.JAXBContextProperties;
19 import org.eclipse.persistence.jaxb.UnmarshallerProperties;
20
21 public class JaxbTestHelper {
22
23     @SuppressWarnings({ "rawtypes", "unchecked" })
24     public static Object jaxbUnmarshall(Object schemaObject, String json) throws JAXBException {
25         Class cls = schemaObject.getClass();
26         Class[] types = new Class[1];
27         types[0] = cls;
28         Map<String, String> namespacePrefixMapper = new HashMap<String, String>(3);
29         namespacePrefixMapper.put("router", "router");
30         namespacePrefixMapper.put("provider", "provider");
31         namespacePrefixMapper.put("binding", "binding");
32         Map<String, Object> jaxbProperties = new HashMap<String, Object>(2);
33         jaxbProperties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
34         jaxbProperties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
35         jaxbProperties.put(JAXBContextProperties.JSON_NAMESPACE_SEPARATOR, ':');
36         jaxbProperties.put(JAXBContextProperties.NAMESPACE_PREFIX_MAPPER, namespacePrefixMapper);
37         JAXBContext jc = JAXBContext.newInstance(types, jaxbProperties);
38
39         Unmarshaller unmarshaller = jc.createUnmarshaller();
40         unmarshaller.setProperty(UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER, namespacePrefixMapper);
41
42         StringReader reader = new StringReader(json);
43         StreamSource stream = new StreamSource(reader);
44         return unmarshaller.unmarshal(stream, cls).getValue();
45     }
46 }