Example usage for javax.xml.bind Unmarshaller setProperty

List of usage examples for javax.xml.bind Unmarshaller setProperty

Introduction

In this page you can find the example usage for javax.xml.bind Unmarshaller setProperty.

Prototype

public void setProperty(String name, Object value) throws PropertyException;

Source Link

Document

Set the particular property in the underlying implementation of Unmarshaller .

Usage

From source file:org.springframework.oxm.jaxb.Jaxb2Marshaller.java

/**
 * Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior.
 * Gets called after creation of JAXB {@code Marshaller}, and after the respective properties have been set.
 * <p>The default implementation sets the {@link #setUnmarshallerProperties(Map) defined properties}, the {@link
 * #setValidationEventHandler(ValidationEventHandler) validation event handler}, the {@link #setSchemas(Resource[])
 * schemas}, {@link #setUnmarshallerListener(javax.xml.bind.Unmarshaller.Listener) listener}, and
 * {@link #setAdapters(XmlAdapter[]) adapters}.
 *//* www .j  a  va2  s  . c  o m*/
protected void initJaxbUnmarshaller(Unmarshaller unmarshaller) throws JAXBException {
    if (this.unmarshallerProperties != null) {
        for (String name : this.unmarshallerProperties.keySet()) {
            unmarshaller.setProperty(name, this.unmarshallerProperties.get(name));
        }
    }
    if (this.unmarshallerListener != null) {
        unmarshaller.setListener(this.unmarshallerListener);
    }
    if (this.validationEventHandler != null) {
        unmarshaller.setEventHandler(this.validationEventHandler);
    }
    if (this.adapters != null) {
        for (XmlAdapter<?, ?> adapter : this.adapters) {
            unmarshaller.setAdapter(adapter);
        }
    }
    if (this.schema != null) {
        unmarshaller.setSchema(this.schema);
    }
}

From source file:org.wso2.carbon.dssapi.observer.APIObserver.java

@Override
public void serviceUpdate(AxisEvent axisEvent, AxisService axisService) {

    if (axisEvent.getEventType() == AxisEvent.SERVICE_DEPLOY) {
        DataService dataService = (DataService) axisService.getParameter(DBConstants.DATA_SERVICE_OBJECT)
                .getValue();// w  w w  .j a  v a2  s  . co  m
        if (dataService != null) {
            String location = dataService.getDsLocation();
            location = location.substring(0, location.lastIndexOf("/"));
            File file = new File(location + "/" + dataService.getName() + APIUtil.APPLICATION_XML);
            if (file.exists()) {
                Application application;
                try {

                    JAXBContext jaxbContext = JAXBContext.newInstance(Application.class);
                    Unmarshaller jaxbUnMarshaller = jaxbContext.createUnmarshaller();
                    jaxbUnMarshaller.setProperty("jaxb.encoding", "UTF-8");
                    application = (Application) jaxbUnMarshaller.unmarshal(file);
                    String serviceContents = new DataServiceAdmin()
                            .getDataServiceContentAsString(dataService.getName());
                    XMLStreamReader reader = XMLInputFactory.newInstance()
                            .createXMLStreamReader(new StringReader(serviceContents));
                    OMElement configElement = (new StAXOMBuilder(reader)).getDocumentElement();
                    configElement.build();
                    Data data = new Data();
                    data.populate(configElement);
                    String tempDeployedTime = new ServiceAdmin(
                            DataHolder.getConfigurationContext().getAxisConfiguration())
                                    .getServiceData(data.getName()).getServiceDeployedTime();
                    if (!application.getDeployedTime().equalsIgnoreCase(tempDeployedTime)) {
                        APIUtil.updateApi(dataService.getName(), application.getUserName(), data,
                                application.getVersion());
                        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
                        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                        jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
                        application.setDeployedTime(tempDeployedTime);
                        jaxbMarshaller.marshal(application, file);
                    }
                } catch (JAXBException e) {
                    log.error("An error occurred while reading the data for " + dataService.getName(), e);
                } catch (XMLStreamException e) {
                    log.error("An error occurred while reading xml data for " + dataService.getName(), e);
                } catch (AxisFault axisFault) {
                    log.error("An error occurred while reading the service " + dataService.getName(),
                            axisFault);
                } catch (Exception e) {
                    log.error("Couldn't get service meta data for the service " + dataService.getName(), e);
                }
                //Logged observed errors and let the process to continue
            }

        }
    }

}

From source file:se.jguru.nazgul.tools.visualization.model.jaxb.PlainJaxbContextRule.java

/**
 * <p>Unmarshals the supplied xmlToUnmarshal into a result of the supplied type, using the given
 * ClassLoader to load all relevant types into the JAXBContext. Typical unarshalling use case involves
 * 2 calls on this PlainJaxbContextRule:</p>
 * <pre>//w  ww  .  j ava  2 s  .c o  m
 *     <code>
 *         // 1) add all types you expect to unmarshal
 *         rule.add(Foo.class, Bar.class, Gnat.class);
 *
 *         // 2) unmarshal your XML string
 *         Foo unmarshalled = rule.unmarshal(getClass().getClassLoader(), Foo.class, aFooXml);
 *     </code>
 * </pre>
 *
 * @param loader          The ClassLoader to use in order to load all classes previously added
 *                        by calls to the {@code add} method.
 * @param assumeJSonInput If {@code true}, the input is assumed to be JSON.
 *                        This requires the EclipseLink MOXy JAXBContextFactory to succeed.
 * @param resultType      The type of the resulting object.
 * @param toUnmarshal     The XML string to unmarshal into a T object.
 * @param <T>             The expected type to unmarshal into.
 * @return The resulting, unmarshalled object.
 * @see #add(Class[])
 */
public <T> T unmarshal(final ClassLoader loader, final boolean assumeJSonInput, final Class<T> resultType,
        final String toUnmarshal) {

    // Check sanity
    Validate.notNull(resultType, "resultType");
    Validate.notEmpty(toUnmarshal, "xmlToUnmarshal");

    final Source source = new StreamSource(new StringReader(toUnmarshal));

    // Use EclipseLink?
    if (assumeJSonInput || useEclipseLinkMOXyIfAvailable) {
        System.setProperty(JAXB_CONTEXTFACTORY_PROPERTY, ECLIPSELINK_JAXB_CONTEXT_FACTORY);
    } else {
        System.clearProperty(JAXB_CONTEXTFACTORY_PROPERTY);
    }

    try {
        jaxbContext = JAXBContext.newInstance(getClasses(loader, null));
    } catch (JAXBException e) {
        throw new IllegalArgumentException("Could not create JAXB context.", e);
    }

    try {
        final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        // Assign all unMarshallerProperties to the Unmarshaller
        unMarshallerProperties.entrySet().stream().forEach(c -> {
            try {
                unmarshaller.setProperty(c.getKey(), c.getValue());
            } catch (PropertyException e) {
                throw new IllegalStateException("Could not assign Unmarshaller property [" + c.getKey()
                        + "] with value [" + c.getValue() + "]", e);
            }
        });

        if (assumeJSonInput) {
            try {
                unmarshaller.setProperty(ECLIPSELINK_MEDIA_TYPE, JSON_CONTENT_TYPE);
                unmarshaller.setProperty(ECLIPSELINK_JSON_WRAPPER_AS_ARRAY_NAME, Boolean.TRUE);
            } catch (PropertyException e) {
                // This is likely not the EclipseLink Marshaller.
            }
        }

        // All Done.
        return unmarshaller.unmarshal(source, resultType).getValue();
    } catch (JAXBException e) {
        throw new IllegalArgumentException("Could not unmarshal xml into [" + resultType.getName() + "]", e);
    }
}

From source file:se.mithlond.services.shared.test.entity.PlainJaxbContextRule.java

/**
 * <p>Unmarshals the supplied xmlToUnmarshal into a result of the supplied type, using the given
 * ClassLoader to load all relevant types into the JAXBContext. Typical unarshalling use case involves
 * 2 calls on this PlainJaxbContextRule:</p>
 * <pre>/* w ww. ja  va 2 s  .  c  o  m*/
 *     <code>
 *         // 1) add all types you expect to unmarshal
 *         rule.add(Foo.class, Bar.class, Gnat.class);
 *
 *         // 2) unmarshal your XML string
 *         Foo unmarshalled = rule.unmarshal(getClass().getClassLoader(), Foo.class, aFooXml);
 *     </code>
 * </pre>
 *
 * @param loader          The ClassLoader to use in order to load all classes previously added
 *                        by calls to the {@code add} method.
 * @param assumeJSonInput If {@code true}, the input is assumed to be JSON.
 *                        This requires the EclipseLink MOXy JAXBContextFactory to succeed.
 * @param resultType      The type of the resulting object.
 * @param toUnmarshal     The XML string to unmarshal into a T object.
 * @param <T>             The expected type to unmarshal into.
 * @return The resulting, unmarshalled object.
 * @see #add(Class[])
 */
public <T> T unmarshal(final ClassLoader loader, final boolean assumeJSonInput, final Class<T> resultType,
        final String toUnmarshal) {

    // Check sanity
    org.apache.commons.lang3.Validate.notNull(resultType, "Cannot handle null 'resultType' argument.");
    org.apache.commons.lang3.Validate.notEmpty(toUnmarshal,
            "Cannot handle null or empty 'xmlToUnmarshal' argument.");

    final Source source = new StreamSource(new StringReader(toUnmarshal));

    // Use EclipseLink?
    if (assumeJSonInput || useEclipseLinkMOXyIfAvailable) {
        System.setProperty(JAXB_CONTEXTFACTORY_PROPERTY, ECLIPSELINK_JAXB_CONTEXT_FACTORY);
    } else {
        System.clearProperty(JAXB_CONTEXTFACTORY_PROPERTY);
    }

    try {
        jaxbContext = JAXBContext.newInstance(getClasses(loader, null), unMarshallerProperties);

        handleNamespacePrefixMapper();

    } catch (JAXBException e) {
        throw new IllegalArgumentException("Could not create JAXB context.", e);
    }

    try {
        final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        // Assign all unMarshallerProperties to the Unmarshaller
        unMarshallerProperties.entrySet().forEach(c -> {
            try {
                unmarshaller.setProperty(c.getKey(), c.getValue());
            } catch (PropertyException e) {
                throw new IllegalStateException("Could not assign Unmarshaller property [" + c.getKey()
                        + "] with value [" + c.getValue() + "]", e);
            }
        });

        if (assumeJSonInput) {
            try {
                unmarshaller.setProperty(ECLIPSELINK_MEDIA_TYPE, JSON_CONTENT_TYPE);
                // unmarshaller.setProperty(ECLIPSELINK_JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE);
            } catch (PropertyException e) {
                // This is likely not the EclipseLink Marshaller.
            }
        }

        // All Done.
        return unmarshaller.unmarshal(source, resultType).getValue();
    } catch (JAXBException e) {
        final String dataType = assumeJSonInput ? "json" : "xml";
        throw new IllegalArgumentException(
                "Could not unmarshal " + dataType + " into [" + resultType.getName() + "]", e);
    }
}