Example usage for javax.xml.bind Marshaller setAdapter

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

Introduction

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

Prototype

public void setAdapter(XmlAdapter adapter);

Source Link

Document

Associates a configured instance of XmlAdapter with this marshaller.

Usage

From source file:BarAdapter.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Foo.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    File xml = new File("data.xml");
    Foo foo = (Foo) unmarshaller.unmarshal(xml);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setAdapter(new BarAdapter());
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(foo, System.out);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Messages.class);

    Messages messages = new Messages();
    messages.getMessages().add(new Message());
    messages.getMessages().add(new Message());
    messages.getMessages().add(new Message());

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setAdapter(new IDAdapter());
    marshaller.marshal(messages, System.out);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Root.class);

    Root rootA = new Root();
    rootA.setName("A");

    Root rootB = new Root();
    rootB.setName("B");
    rootA.setChild(rootB);/*ww w  . j a  v  a 2 s .c  om*/

    Root rootC = new Root();
    rootC.setName("C");
    rootB.setChild(rootC);

    Root rootD = new Root();
    rootD.setName("D");
    rootC.setChild(rootD);

    Root rootE = new Root();
    rootE.setName("E");
    rootD.setChild(rootE);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    DepthListener depthListener = new DepthListener(3);
    marshaller.setListener(depthListener);
    marshaller.setAdapter(new RootAdapter(depthListener));
    marshaller.marshal(rootA, System.out);
}

From source file:com.rapid.server.RapidHttpServlet.java

public static Marshaller getMarshaller() throws JAXBException, IOException {
    // marshaller is not thread safe so we need to create a new one each time
    Marshaller marshaller = _jaxbContext.createMarshaller();
    // add the encrypted xml adapter
    marshaller.setAdapter(_encryptedXmlAdapter);
    // return/* ww  w . j av a  2  s . c om*/
    return marshaller;
}

From source file:org.betaconceptframework.astroboa.model.jaxb.CmsEntitySerialization.java

public Marshaller createMarshaller(ResourceRepresentationType<?> resourceRepresentationType,
        boolean prettyPrint) throws JAXBException {

    boolean jsonResourceRepresentationType = resourceRepresentationType != null
            && ResourceRepresentationType.JSON.equals(resourceRepresentationType);

    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setListener(new AstroboaMarshalListener(jsonResourceRepresentationType));

    if (jsonResourceRepresentationType) {
        LocalizationAdapter localizationAdapter = new LocalizationAdapter();
        localizationAdapter.useJsonVersion();
        marshaller.setAdapter(localizationAdapter);
    }//from w  w  w . j  a  v  a  2 s .c  o  m

    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, prettyPrint);

    return new AstroboaMarshaller(marshaller, resourceRepresentationType);
}

From source file:org.betaconceptframework.astroboa.model.jaxb.CmsEntitySerialization.java

private String marshalEntity(CmsRepositoryEntity cmsRepositoryEntity,
        ResourceRepresentationType<?> resourceRepresentationType, boolean exportBinaryContent,
        boolean prettyPrint, String... propertyPathsToBeMarshalled) {

    if (cmsRepositoryEntity != null) {

        if (cmsRepositoryEntity instanceof ContentObject || cmsRepositoryEntity instanceof Topic
                || cmsRepositoryEntity instanceof Space || cmsRepositoryEntity instanceof RepositoryUser
                || cmsRepositoryEntity instanceof Taxonomy) {

            StringWriter writer = new StringWriter();

            Marshaller marshaller = null;
            try {
                marshaller = createMarshaller(resourceRepresentationType, prettyPrint);

                if (cmsRepositoryEntity instanceof ContentObject) {

                    if (!ArrayUtils.isEmpty(propertyPathsToBeMarshalled)) {
                        marshaller.setProperty(AstroboaMarshaller.CMS_PROPERTIES_TO_BE_MARSHALLED,
                                Arrays.asList(propertyPathsToBeMarshalled));
                    }//from   w  w w.j ava  2s. co m

                    //ContentObject needs special marshaling as JAXB does not have
                    //enough information in order to initialize appropriate adapter for
                    //ContentObject
                    ContentObjectAdapter adapter = new ContentObjectAdapter();
                    adapter.setMarshaller(marshaller, exportBinaryContent,
                            ArrayUtils.isEmpty(propertyPathsToBeMarshalled));

                    marshaller.setAdapter(adapter);

                    ContentObjectType contentObjectType = marshaller.getAdapter(ContentObjectAdapter.class)
                            .marshal((ContentObject) cmsRepositoryEntity);

                    JAXBElement<ContentObjectType> contentObjectTypeJaxb = new JAXBElement<ContentObjectType>(
                            ((ContentObject) cmsRepositoryEntity).getTypeDefinition().getQualifiedName(),
                            ContentObjectType.class, null, contentObjectType);

                    marshaller.marshal(contentObjectTypeJaxb, writer);
                } else {

                    //Provide schema location 
                    marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, " "
                            + BetaConceptNamespaceConstants.ASTROBOA_MODEL_DEFINITION_URI + " "
                            + SchemaUtils.buildSchemaLocationForAstroboaModelSchemaAccordingToActiveClient());

                    marshaller.marshal(cmsRepositoryEntity, writer);
                }

            } catch (Exception e) {
                throw new CmsException(e);
            } finally {

                marshaller = null;
            }

            return writer.toString();
        } else {
            throw new CmsException("Creating XML for entity type " + cmsRepositoryEntity.getClass().getName()
                    + " is not supported");
        }
    }

    throw new CmsException("No entity is provided. Unable to create xml");
}

From source file:org.betaconceptframework.astroboa.model.jaxb.visitor.ContentObjectMarshalVisitor.java

protected <T> void marshallValueForSimpleProperty(SimpleCmsPropertyDefinition<T> simplePropertyDefinition,
        CmsPropertyInfo simpleCmsProperty, Object value) {

    if (value != null) {

        switch (simplePropertyDefinition.getValueType()) {
        case String:
        case Boolean:
        case Double:
        case Long:
        case Date:

            final SimpleCmsPropertyType simpleCmsPropertyType = new SimpleCmsPropertyType();

            simpleCmsPropertyType.setExportAsAnAttribute(
                    ((SimpleCmsPropertyDefinitionImpl) simplePropertyDefinition).isRepresentsAnXmlAttribute());

            if (marshalOutputTypeIsJSON() && simplePropertyDefinition.isMultiple()) {
                simpleCmsPropertyType.setExportAsAnArray(true);
            }/*from  w  w  w.j a va 2s .c om*/

            CmsPropertyTypeJAXBElement<SimpleCmsPropertyType> simpleCmsPropertyTypeJaxbElement = new CmsPropertyTypeJAXBElement(
                    new QName(simplePropertyDefinition.getQualifiedName().getLocalPart()),
                    SimpleCmsPropertyType.class, null, simpleCmsPropertyType);

            if (value instanceof String) {
                simpleCmsPropertyTypeJaxbElement.getValue().setContent((String) value);
            } else if (value instanceof Boolean) {
                simpleCmsPropertyTypeJaxbElement.getValue().setContent(((Boolean) value).toString());
            } else if (value instanceof Double) {
                simpleCmsPropertyTypeJaxbElement.getValue().setContent(((Double) value).toString());
            } else if (value instanceof Long) {
                simpleCmsPropertyTypeJaxbElement.getValue().setContent(((Long) value).toString());
            } else if (value instanceof Calendar) {
                Calendar calendar = (Calendar) value;

                try {
                    if (((CalendarPropertyDefinition) simplePropertyDefinition).isDateTime()) {
                        GregorianCalendar gregCalendar = new GregorianCalendar(calendar.getTimeZone());
                        gregCalendar.setTimeInMillis(calendar.getTimeInMillis());

                        simpleCmsPropertyTypeJaxbElement.getValue()
                                .setContent(df.newXMLGregorianCalendar(gregCalendar).toXMLFormat());
                    } else {
                        simpleCmsPropertyTypeJaxbElement.getValue()
                                .setContent(df.newXMLGregorianCalendarDate(calendar.get(Calendar.YEAR),
                                        calendar.get(Calendar.MONTH) + 1, // Calendar.MONTH is zero based, XSD Date datatype's month field starts
                                        //   with JANUARY as 1.
                                        calendar.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED)
                                        .toXMLFormat());
                    }
                } catch (Exception e) {
                    throw new CmsException("Property " + simpleCmsProperty.getFullPath() + " Calendar value "
                            + DateUtils.format(calendar), e);
                }
            } else {
                throw new CmsException("Property " + simpleCmsProperty.getFullPath() + " has value type "
                        + simplePropertyDefinition.getValueType() + " but contains value of type "
                        + value.getClass().getName());
            }

            addJaxbElementToCurrentParentComplexCmsPropertyType(simpleCmsPropertyTypeJaxbElement);

            break;
        case TopicReference:

            try {
                TopicType topicType = marshalTopicReference(value);

                if (marshalOutputTypeIsJSON() && simplePropertyDefinition.isMultiple()) {
                    topicType.setExportAsAnArray(true);
                }

                CmsPropertyTypeJAXBElement<TopicType> topicTypeJaxbElement = new CmsPropertyTypeJAXBElement(
                        new QName(simplePropertyDefinition.getQualifiedName().getLocalPart()), TopicType.class,
                        null, topicType);

                addJaxbElementToCurrentParentComplexCmsPropertyType(topicTypeJaxbElement);

            } catch (Exception e) {
                throw new CmsException("Unable to marshal topic " + ((Topic) value).getName(), e);
            }

            break;
        case Binary:
            try {
                BinaryChannelType binaryChannelType = getBinaryChannelAdapter().marshal((BinaryChannel) value);

                if (marshalOutputTypeIsJSON() && simplePropertyDefinition.isMultiple()) {
                    binaryChannelType.setExportAsAnArray(true);
                }

                CmsPropertyTypeJAXBElement<BinaryChannelType> binaryChannelTypeJaxbElement = new CmsPropertyTypeJAXBElement(
                        new QName(simplePropertyDefinition.getQualifiedName().getLocalPart()),
                        BinaryChannelType.class, null, binaryChannelType);

                addJaxbElementToCurrentParentComplexCmsPropertyType(binaryChannelTypeJaxbElement);

            } catch (Exception e) {
                throw new CmsException("Unable to marshal binary channel " + ((BinaryChannel) value).getName(),
                        e);
            }

            break;
        case ObjectReference:
            try {

                logger.debug("\t Property is a reference to another object");

                Marshaller objectReferenceMarshaller = CmsEntitySerialization.Context
                        .createMarshaller(marshalOutputTypeIsJSON() ? ResourceRepresentationType.JSON
                                : ResourceRepresentationType.XML, prettyPrintIsEnabled());

                //For now only porifle.title is provided. 
                objectReferenceMarshaller.setProperty(AstroboaMarshaller.CMS_PROPERTIES_TO_BE_MARSHALLED,
                        Arrays.asList("profile.title"));

                ContentObjectAdapter adapter = new ContentObjectAdapter();
                adapter.setMarshaller(objectReferenceMarshaller, marshallBinaryContent, false);
                objectReferenceMarshaller.setAdapter(adapter);

                ContentObjectType contentObjectType = objectReferenceMarshaller
                        .getAdapter(ContentObjectAdapter.class).marshal((ContentObject) value);

                if (marshalOutputTypeIsJSON() && simplePropertyDefinition.isMultiple()) {
                    contentObjectType.setExportAsAnArray(true);
                }

                CmsPropertyTypeJAXBElement<ContentObjectType> contentObjectReferenceTypeJaxbElement = new CmsPropertyTypeJAXBElement(
                        new QName(simplePropertyDefinition.getQualifiedName().getLocalPart()),
                        ContentObjectType.class, null, contentObjectType);

                addJaxbElementToCurrentParentComplexCmsPropertyType(contentObjectReferenceTypeJaxbElement);

            } catch (Exception e) {
                throw new CmsException("Unable to marshal contentObject " + ((ContentObject) value).getId(), e);
            }

            break;
        default:
            break;
        }

    }
}

From source file:org.codice.ddf.parser.xml.XmlParser.java

private void marshal(ParserConfigurator configurator, Consumer<Marshaller> marshallerConsumer)
        throws ParserException {
    JAXBContext jaxbContext = getContext(configurator.getContextPath(), configurator.getClassLoader());

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    try {/*ww w  . j  a va 2 s  .c om*/
        Thread.currentThread().setContextClassLoader(configurator.getClassLoader());
        Marshaller marshaller = jaxbContext.createMarshaller();
        if (configurator.getAdapter() != null) {
            marshaller.setAdapter(configurator.getAdapter());
        }
        if (configurator.getHandler() != null) {
            marshaller.setEventHandler(configurator.getHandler());
        }
        for (Map.Entry<String, Object> propRow : configurator.getProperties().entrySet()) {
            marshaller.setProperty(propRow.getKey(), propRow.getValue());
        }

        marshallerConsumer.accept(marshaller);
    } catch (RuntimeException e) {
        LOGGER.error("Error marshalling ", e);
        throw new ParserException("Error marshalling ", e);
    } catch (JAXBException e) {
        LOGGER.error("Error marshalling ", e);
        throw new ParserException("Error marshalling", e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }
}

From source file:org.fuin.units4j.Units4JUtils.java

/**
 * Marshals the given data using a given context. A <code>null</code> data
 * argument returns <code>null</code>.
 * /*from  w  w  w.  ja  va  2  s . c  om*/
 * @param ctx
 *            Context to use.
 * @param data
 *            Data to serialize or <code>null</code>.
 * @param adapters
 *            Adapters to associate with the marshaller or
 *            <code>null</code>.
 * 
 * @return XML data or <code>null</code>.
 * 
 * @param <T>
 *            Type of the data.
 */
public static <T> String marshal(@NotNull final JAXBContext ctx, final T data,
        final XmlAdapter<?, ?>[] adapters) {
    if (data == null) {
        return null;
    }
    try {
        final Marshaller marshaller = ctx.createMarshaller();
        if (adapters != null) {
            for (XmlAdapter<?, ?> adapter : adapters) {
                marshaller.setAdapter(adapter);
            }
        }
        final StringWriter writer = new StringWriter();
        marshaller.marshal(data, writer);
        return writer.toString();
    } catch (final JAXBException ex) {
        throw new RuntimeException("Error marshalling test data", ex);
    }
}

From source file:org.osate.atsv.integration.EngineConfigModel.ExplorationEngineModel.java

public void renderConfigurator() throws JAXBException, UnsatisfiableConstraint,
        ConfiguratorRepresentationException, UnsupportedFeatureException {
    if (cm.isEmpty()) {
        configurator = "";
        return;//w  ww  . ja v  a2  s  . com
    }
    JAXBContext context = JAXBContext.newInstance(ConfiguratorsModel.class, SimpleConfiguratorModel.class,
            ImpliesConfiguratorModel.class, SetRestrictionConfiguratorModel.class);
    ConfiguratorModelAdapter configuratorAdapter = new ConfiguratorModelAdapter();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Marshaller marshal = context.createMarshaller();
    marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
    marshal.setProperty(Marshaller.JAXB_FRAGMENT, true);
    marshal.setAdapter(configuratorAdapter);
    JAXBElement<ConfiguratorsModel> configuratorXML = new JAXBElement<ConfiguratorsModel>(
            new QName("Configurator"), ConfiguratorsModel.class, cm);
    marshal.marshal(configuratorXML, stream);
    configurator = stream.toString();
}