Example usage for javax.xml.bind Marshaller setSchema

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

Introduction

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

Prototype

public void setSchema(Schema schema);

Source Link

Document

Specify the JAXP 1.3 javax.xml.validation.Schema Schema object that should be used to validate subsequent marshal operations against.

Usage

From source file:MarshalValidation.java

public static void main(String[] args) throws Exception {
    Person p = new Person();
    p.setFirstName("B");
    p.setLastName("H");

    JAXBContext context = JAXBContext.newInstance(Person.class);
    Marshaller marshaller = context.createMarshaller();

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new File("person.xsd"));

    marshaller.setSchema(schema);
    marshaller.setEventHandler(new ValidationEventHandler() {
        public boolean handleEvent(ValidationEvent event) {
            System.out.println(event);
            return false;
        }//from  w  ww .j a v  a2 s. c  om
    });

    marshaller.marshal(p, System.out);
}

From source file:Main.java

public static Marshaller createMarshaller(String pack, Schema schema) {
    JAXBContext jaxbContext = null;
    try {/*from   ww  w.jav  a 2  s .c o  m*/
        jaxbContext = JAXBContext.newInstance(pack);
        Marshaller marsh = jaxbContext.createMarshaller();

        if (schema != null) {
            marsh.setSchema(schema);
            //                marsh.setEventHandler( new DefaultValidationEventHandler() {
            //                    @Override
            //                    public boolean handleEvent( ValidationEvent event ) {
            //                        return super.handleEvent( event );
            //                    }
            //                });
        }
        marsh.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        return marsh;
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

@SuppressWarnings("rawtypes")
public static void marshal(Object object, Writer w) throws JAXBException {
    Class clazz = object.getClass();
    JAXBContext context = s_contexts.get(clazz);
    if (context == null) {
        context = JAXBContext.newInstance(clazz);
        s_contexts.put(clazz, context);// ww w  .  j  a v  a2s . c  o m
    }

    ValidationEventCollector valEventHndlr = new ValidationEventCollector();
    Marshaller marshaller = context.createMarshaller();
    marshaller.setSchema(null);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setEventHandler(valEventHndlr);

    try {
        marshaller.marshal(object, w);
    } catch (Exception e) {
        if (e instanceof JAXBException) {
            throw (JAXBException) e;
        } else {
            throw new MarshalException(e.getMessage(), e);
        }
    }
    if (valEventHndlr.hasEvents()) {
        for (ValidationEvent valEvent : valEventHndlr.getEvents()) {
            if (valEvent.getSeverity() != ValidationEvent.WARNING) {
                // throw a new Marshall Exception if there is a parsing error
                throw new MarshalException(valEvent.getMessage(), valEvent.getLinkedException());
            }
        }
    }
}

From source file:Main.java

@SuppressWarnings("rawtypes")
public static String ObjToXml(Object object, boolean isXmlFormat, Class... classesToBeBound)
        throws JAXBException, IOException {
    JAXBContext context = JAXBContext.newInstance(classesToBeBound);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, isXmlFormat);
    m.setSchema(null);
    StringWriter sw = new StringWriter();
    m.marshal(object, sw);//from   w  ww.  j ava2  s .c o m
    String result = sw.toString();
    sw.close();
    return result;
}

From source file:Main.java

public static String getXmlString(JAXBElement versioningInfo, Boolean formatXml, Schema schema)
        throws JAXBException {
    String packageName = versioningInfo.getValue().getClass().getPackage().getName();
    JAXBContext context = JAXBContext.newInstance(packageName);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatXml);

    if (schema != null) {
        marshaller.setSchema(schema);
    }//from w w  w  .  ja va  2  s .c  o  m

    ByteArrayOutputStream oStream = new ByteArrayOutputStream();
    marshaller.marshal(versioningInfo, oStream);

    return oStream.toString();
}

From source file:org.vincibean.salestaxes.jaxb.JaxbFactory.java

/**
 * Factory method, creates a {@link Marshaller} from the context given in the constructor; moreover, ensure that
 * the marshalled XML data is formatted with linefeeds and indentation.  
 * @return an {@link Optional} object which may or may not contain a {@link Marshaller}
 *//*  w  w  w . j a v a2  s. c  o m*/
public static Optional<Marshaller> createMarshaller(final Class<?> context) {
    try {
        Marshaller marshaller = JAXBContext.newInstance(context).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new ClassPathResource("receipt/Poiuyt.xsd").getFile()));
        marshaller.setEventHandler(new FoobarValidationEventHandler());
        return Optional.fromNullable(marshaller);
    } catch (JAXBException | SAXException | IOException e) {
        logger.warn("Exception on jaxb factory creation: ", e);
        return Optional.absent();
    }
}

From source file:de.iteratec.iteraplan.businesslogic.service.SavedQueryXmlHelper.java

private static Marshaller getMarshaller(Class<?> clazz, String schemaName) throws JAXBException, SAXException {
    JAXBContext context = JAXBContext.newInstance(clazz);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.setSchema(getSchema(schemaName));
    m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, SCHEMA_URI + " " + SCHEMA_URI + schemaName);

    return m;/*from   www.j ava 2 s  .  c  o  m*/
}

From source file:Main.java

/**
 * Generic method to Validate XML file while marshalling against their schema.
 * // w  w  w . j  av  a 2  s .c o  m
 * @param context
 * @param schemaFile
 * @param object
 * @return
 * @throws SAXException
 * @throws JAXBException
 */
public static String validateAndMarshallXML(JAXBContext context, String schemaFile, Object object)
        throws SAXException, JAXBException {
    String xmlFormOfBean = null;

    if (context != null && (schemaFile != null && schemaFile.trim().length() > 0)) {
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // thread- safe 
        marshaller.setSchema(sf.newSchema(new File(schemaFile))); // validate jaxb context against schema 
        ByteArrayOutputStream sos = new ByteArrayOutputStream(); // for XML output into string

        marshaller.marshal(object, sos);
        xmlFormOfBean = sos.toString();

    }
    return xmlFormOfBean;
}

From source file:com.mymita.vaadlets.JAXBUtils.java

private static final void marshal(final Writer aWriter, final Vaadlets vaadlets,
        final Resource theSchemaResource) {
    try {//from   w  w  w. j a v  a  2s .co  m
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Marshaller marshaller = jc.createMarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            marshaller.setSchema(schema);
        }
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
                new com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper() {

                    @Override
                    public String getPreferredPrefix(final String namespaceUri, final String suggestion,
                            final boolean requirePrefix) {
                        final String subpackage = namespaceUri.replaceFirst("http://www.mymita.com/vaadlets/",
                                "");
                        if (subpackage.equals("1.0.0")) {
                            return "";
                        }
                        return Iterables.getFirst(newArrayList(Splitter.on("/").split(subpackage).iterator()),
                                "");
                    }
                });
        marshaller.marshal(
                new JAXBElement<Vaadlets>(new QName("http://www.mymita.com/vaadlets/1.0.0", "vaadlets", ""),
                        Vaadlets.class, vaadlets),
                aWriter);
    } catch (final JAXBException | SAXException | FactoryConfigurationError | IOException e) {
        throw new RuntimeException("Can't marschal", e);
    }
}

From source file:com.netxforge.oss2.core.xml.JaxbUtils.java

public static Marshaller getMarshallerFor(final Object obj, final JAXBContext jaxbContext) {
    final Class<?> clazz = (Class<?>) (obj instanceof Class<?> ? obj : obj.getClass());

    Map<Class<?>, Marshaller> marshallers = m_marshallers.get();
    if (jaxbContext == null) {
        if (marshallers == null) {
            marshallers = new WeakHashMap<Class<?>, Marshaller>();
            m_marshallers.set(marshallers);
        }/*from   w  w  w.j  av  a 2s .c om*/
        if (marshallers.containsKey(clazz)) {
            LogUtils.tracef(clazz, "found unmarshaller for %s", clazz);
            return marshallers.get(clazz);
        }
    }
    LogUtils.tracef(clazz, "creating unmarshaller for %s", clazz);

    try {
        final JAXBContext context;
        if (jaxbContext == null) {
            context = getContextFor(clazz);
        } else {
            context = jaxbContext;
        }
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        final Schema schema = getValidatorFor(clazz);
        marshaller.setSchema(schema);
        if (jaxbContext == null)
            marshallers.put(clazz, marshaller);

        return marshaller;
    } catch (JAXBException e) {
        throw EXCEPTION_TRANSLATOR.translate("creating XML marshaller", e);
    }
}