Bump upstream versions
[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.Collections;
13 import java.util.HashMap;
14 import java.util.List;
15 import java.util.Map;
16 import javax.xml.bind.JAXBContext;
17 import javax.xml.bind.JAXBException;
18 import javax.xml.bind.Unmarshaller;
19 import javax.xml.transform.stream.StreamSource;
20 import org.eclipse.persistence.jaxb.JAXBContextProperties;
21 import org.eclipse.persistence.jaxb.UnmarshallerProperties;
22
23 public final class JaxbTestHelper {
24
25     private JaxbTestHelper() {
26     }
27
28     public static <T> T jaxbUnmarshall(Class<T> schemaClass, String json) throws JAXBException {
29         Map<String, String> namespacePrefixMapper = new HashMap<>(3);
30         namespacePrefixMapper.put("router", "router");
31         namespacePrefixMapper.put("provider", "provider");
32         namespacePrefixMapper.put("binding", "binding");
33
34         Map<String, Object> jaxbProperties = new HashMap<>(2);
35         jaxbProperties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
36         jaxbProperties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
37         jaxbProperties.put(JAXBContextProperties.JSON_NAMESPACE_SEPARATOR, ':');
38         jaxbProperties.put(JAXBContextProperties.NAMESPACE_PREFIX_MAPPER, namespacePrefixMapper);
39
40         List<Class<T>> classesToBeBound = Collections.singletonList(schemaClass);
41         JAXBContext jc = JAXBContext.newInstance(classesToBeBound.toArray(new Class[0]), jaxbProperties);
42
43         Unmarshaller unmarshaller = jc.createUnmarshaller();
44         unmarshaller.setProperty(UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER, namespacePrefixMapper);
45
46         try (StringReader reader = new StringReader(json)) {
47             StreamSource stream = new StreamSource(reader);
48             T object = unmarshaller.unmarshal(stream, schemaClass).getValue();
49             if (object == null) {
50                 throw new IllegalStateException(
51                         "unmarshal() returned null for arguments schemaClass=" + schemaClass + ", json: " + json);
52             } else {
53                 return object;
54             }
55         }
56     }
57 }