2 * Copyright (C) 2015 IBM, Inc.
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
9 package org.opendaylight.neutron.spi;
11 import java.io.StringReader;
12 import java.util.Collections;
13 import java.util.HashMap;
14 import java.util.List;
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;
23 public final class JaxbTestHelper {
25 private JaxbTestHelper() {
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");
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);
40 List<Class<T>> classesToBeBound = Collections.singletonList(schemaClass);
41 JAXBContext jc = JAXBContext.newInstance(classesToBeBound.toArray(new Class[0]), jaxbProperties);
43 Unmarshaller unmarshaller = jc.createUnmarshaller();
44 unmarshaller.setProperty(UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER, namespacePrefixMapper);
46 try (StringReader reader = new StringReader(json)) {
47 StreamSource stream = new StreamSource(reader);
48 T object = unmarshaller.unmarshal(stream, schemaClass).getValue();
50 throw new IllegalStateException(
51 "unmarshal() returned null for arguments schemaClass=" + schemaClass + ", json: " + json);