Example usage for javax.xml.bind Marshaller getClass

List of usage examples for javax.xml.bind Marshaller getClass

Introduction

In this page you can find the example usage for javax.xml.bind Marshaller getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:be.fedict.eid.tsl.TrustServiceList.java

private void marshall() throws JAXBException, ParserConfigurationException {
    /*//from w  w w .  j  a  va  2s  . c om
     * Assign a unique XML Id to the TSL for signing purposes.
     */
    String tslId = "tsl-" + UUID.randomUUID().toString();
    TrustStatusListType trustStatusList = getTrustStatusList();
    trustStatusList.setId(tslId);

    /*
     * TSLTag
     */
    trustStatusList.setTSLTag(TSL_TAG);

    /*
     * Scheme Information - TSL version identifier.
     */
    TSLSchemeInformationType schemeInformation = trustStatusList.getSchemeInformation();
    if (null == schemeInformation) {
        schemeInformation = this.objectFactory.createTSLSchemeInformationType();
        trustStatusList.setSchemeInformation(schemeInformation);
    }
    schemeInformation.setTSLVersionIdentifier(BigInteger.valueOf(4));

    /*
     * Scheme Information - TSL sequence number
     */
    if (null == schemeInformation.getTSLSequenceNumber()) {
        schemeInformation.setTSLSequenceNumber(BigInteger.valueOf(1));
    }

    /*
     * Scheme Information - TSL Type
     */
    schemeInformation.setTSLType(TSL_TYPE);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,
            be.fedict.eid.tsl.jaxb.ecc.ObjectFactory.class, be.fedict.eid.tsl.jaxb.tslx.ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    LOG.debug("marshaller type: " + marshaller.getClass().getName());
    marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new TSLNamespacePrefixMapper());
    ObjectFactory objectFactory = new ObjectFactory();
    JAXBElement<TrustStatusListType> trustStatusListElement = objectFactory
            .createTrustServiceStatusList(trustStatusList);
    marshaller.marshal(trustStatusListElement, document);

    this.tslDocument = document;
}

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

/**
 * Marshals the supplied objects into an XML String, or throws an IllegalArgumentException
 * containing a wrapped JAXBException indicating why the marshalling was unsuccessful.
 *
 * @param loader   The ClassLoader to use in order to load all classes previously added
 *                 by calls to the {@code add} method.
 * @param emitJSON if {@code true}, the method will attempt to output JSON instead of XML.
 *                 This requires the EclipseLink MOXy implementation as the JAXBContextFactory.
 * @param objects  The objects to Marshal into XML.
 * @return An XML-formatted String containing
 * @throws IllegalArgumentException if the marshalling operation failed.
 *                                  The {@code cause} field in the IllegalArgumentException contains
 *                                  the JAXBException thrown by the JAXB framework.
 * @see #add(Class[])/*w w w .  j  a  va2s  .  c o m*/
 */
@SuppressWarnings("all")
public String marshal(final ClassLoader loader, final boolean emitJSON, final Object... objects)
        throws IllegalArgumentException {

    // Create an EntityTransporter, to extract the types as required by the plain JAXBContext.
    final EntityTransporter<Object> transporter = new EntityTransporter<>();
    for (Object current : objects) {
        transporter.addItem(current);
    }

    // Use EclipseLink?
    if (emitJSON) {
        setUseEclipseLinkMOXyIfAvailable(true);
    }
    if (useEclipseLinkMOXyIfAvailable) {
        System.setProperty(JAXB_CONTEXTFACTORY_PROPERTY, ECLIPSELINK_JAXB_CONTEXT_FACTORY);
    } else {
        System.clearProperty(JAXB_CONTEXTFACTORY_PROPERTY);
    }

    // Extract class info as required by the JAXBContext.
    final SortedSet<String> clsInfo = transporter.getClassInformation();
    try {
        jaxbContext = JAXBContext.newInstance(getClasses(loader, clsInfo), marshallerProperties);

        log.info("Got JAXBContext of type " + jaxbContext.getClass().getName() + ", with classes");

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

    // Handle the namespace mapper
    handleNamespacePrefixMapper();

    Marshaller marshaller = null;
    try {
        marshaller = jaxbContext.createMarshaller();

        // Should we validate what we write?
        if (performXsdValidation) {

            if ("org.eclipse.persistence.jaxb.JAXBContext".equals(jaxbContext.getClass().getName())) {

                // Cast to the appropriate JAXBContext
                org.eclipse.persistence.jaxb.JAXBContext eclipseLinkJaxbContext = ((org.eclipse.persistence.jaxb.JAXBContext) jaxbContext);
                if (emitJSON) {

                    final SimpleSchemaOutputResolver simpleResolver = new SimpleSchemaOutputResolver();
                    Arrays.stream(objects).filter(c -> c != null).forEach(c -> {

                        final Class<?> currentClass = c.getClass();

                        if (log.isDebugEnabled()) {
                            log.debug("Generating JSON schema for " + currentClass.getName());
                        }
                        try {
                            eclipseLinkJaxbContext.generateJsonSchema(simpleResolver, currentClass);
                        } catch (Exception e) {
                            log.error("Could not generate JSON schema", e);
                        }
                    });
                } else {
                    final Tuple<Schema, LSResourceResolver> schema2LSResolver = generateTransientXSD(
                            jaxbContext);
                    marshaller.setSchema(schema2LSResolver.getKey());
                }
            }
        }

    } catch (Exception e) {

        try {
            marshaller = jaxbContext.createMarshaller();
        } catch (JAXBException e1) {

            throw new IllegalStateException("Could not create non-validating JAXB Marshaller", e);
        }
    }

    // Should we emit JSON instead of XML?
    if (emitJSON) {
        try {
            marshaller.setProperty(ECLIPSELINK_MEDIA_TYPE, JSON_CONTENT_TYPE);
            marshaller.setProperty(ECLIPSELINK_JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE);
        } catch (PropertyException e) {

            // This is likely not the EclipseLink Marshaller.
            log.error(
                    "Could not assign EclipseLink properties to Marshaller of type "
                            + marshaller.getClass().getName() + "]. Proceeding, but results may be unexpected.",
                    e);
        }
    }

    // Assign all other Marshaller properties.
    try {
        for (Map.Entry<String, Object> current : marshallerProperties.entrySet()) {
            marshaller.setProperty(current.getKey(), current.getValue());
        }
    } catch (PropertyException e) {
        final StringBuilder builder = new StringBuilder("Could not assign Marshaller properties.");
        marshallerProperties.entrySet().stream()
                .forEach(c -> builder.append("\n  [" + c.getKey() + "]: " + c.getValue()));

        throw new IllegalStateException(builder.toString(), e);
    }

    // Marshal the objects
    final StringWriter result = new StringWriter();
    for (int i = 0; i < objects.length; i++) {
        final StringWriter tmp = new StringWriter();
        try {
            marshaller.marshal(objects[i], tmp);
            result.write(tmp.toString());
        } catch (JAXBException e) {
            final String currentTypeName = objects[i] == null ? "<null>" : objects[i].getClass().getName();
            throw new IllegalArgumentException(
                    "Could not marshalToXML object [" + i + "] of type [" + currentTypeName + "].", e);
        } catch (Exception e) {
            throw new IllegalArgumentException("Could not marshalToXML object [" + i + "]: " + objects[i], e);
        }
    }

    // All done.
    return result.toString();
}