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:org.pesc.cds.service.TranscriptAcknowledgementService.java

public String toXml(Acknowledgment acknowledgment) {
    try {/*  w ww.  j a  v  a  2s  .co  m*/

        Marshaller marshaller = serializationService.createTranscriptAckMarshaller();
        Schema schema = ValidationUtils.getSchema(XmlFileType.TRANSCRIPT_ACKNOWLEDGEMENT,
                XmlSchemaVersion.V1_3_0);

        marshaller.setSchema(schema);

        StringWriter writer = new StringWriter();
        marshaller.marshal(acknowledgment, writer);

        return writer.toString();

    } catch (JAXBException e) {
        log.error(e);
    } catch (SAXException e) {
        log.error(e);
    } catch (OperationNotSupportedException e) {
        log.error(e);
    }

    return null;
}

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 #setMarshallerProperties(Map) defined properties}, the {@link
 * #setValidationEventHandler(ValidationEventHandler) validation event handler}, the {@link #setSchemas(Resource[])
 * schemas}, {@link #setMarshallerListener(javax.xml.bind.Marshaller.Listener) listener}, and
 * {@link #setAdapters(XmlAdapter[]) adapters}.
 *//*from   www  .j a v a 2  s. co  m*/
protected void initJaxbMarshaller(Marshaller marshaller) throws JAXBException {
    if (this.marshallerProperties != null) {
        for (String name : this.marshallerProperties.keySet()) {
            marshaller.setProperty(name, this.marshallerProperties.get(name));
        }
    }
    if (this.marshallerListener != null) {
        marshaller.setListener(this.marshallerListener);
    }
    if (this.validationEventHandler != null) {
        marshaller.setEventHandler(this.validationEventHandler);
    }
    if (this.adapters != null) {
        for (XmlAdapter<?, ?> adapter : this.adapters) {
            marshaller.setAdapter(adapter);
        }
    }
    if (this.schema != null) {
        marshaller.setSchema(this.schema);
    }
}

From source file:org.tridas.io.formats.tridasjson.TridasJSONFile.java

public void validate() throws ImpossibleConversionException {
    Schema schema = null;//w ww.j  a v a  2 s. co  m

    // Validate output against schema first
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL file = IOUtils.getFileInJarURL("schemas/tridas.xsd");
    if (file == null) {
        log.error("Could not find schema file");
    } else {
        try {
            schema = factory.newSchema(file);
        } catch (SAXException e) {
            log.error("Error getting TRiDaS schema for validation, not using.", e);
            throw new ImpossibleConversionException(I18n.getText("fileio.errorGettingSchema"));
        }
    }

    swriter = new StringWriter();
    // Marshaller code goes here...
    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance("org.tridas.schema");
        Marshaller m = jc.createMarshaller();
        m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new TridasNamespacePrefixMapper());
        if (schema != null) {
            m.setSchema(schema);
        }
        m.marshal(getTridasContainer(), swriter);

    } catch (Exception e) {
        log.error("Jaxb error", e);

        String cause = e.getCause().getMessage();
        if (cause != null) {
            throw new ImpossibleConversionException(I18n.getText("fileio.jaxbError") + " " + cause);
        } else {
            throw new ImpossibleConversionException(I18n.getText("fileio.jaxbError"));
        }

    }

}

From source file:org.voltdb.utils.CatalogUtil.java

/**
 * Given the deployment object generate the XML
 * @param deployment//from ww  w .j  av a 2 s. c o  m
 * @return XML of deployment object.
 * @throws IOException
 */
public static String getDeployment(DeploymentType deployment) throws IOException {
    try {
        if (m_jc == null || m_schema == null) {
            throw new RuntimeException("Error schema validation.");
        }
        Marshaller marshaller = m_jc.createMarshaller();
        marshaller.setSchema(m_schema);
        StringWriter sw = new StringWriter();
        marshaller.marshal(new JAXBElement(new QName("", "deployment"), DeploymentType.class, deployment), sw);
        return sw.toString();
    } catch (JAXBException e) {
        // Convert some linked exceptions to more friendly errors.
        if (e.getLinkedException() instanceof java.io.FileNotFoundException) {
            hostLog.error(e.getLinkedException().getMessage());
            return null;
        } else if (e.getLinkedException() instanceof org.xml.sax.SAXParseException) {
            hostLog.error(
                    "Error schema validating deployment.xml file. " + e.getLinkedException().getMessage());
            return null;
        } else {
            throw new RuntimeException(e);
        }
    }
}

From source file:se.jguru.nazgul.tools.visualization.model.jaxb.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 schema   An optional (i.e. nullable) Schema, used to validate output from the Marshaller.
 * @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[])/*from w w  w.  j  a v a  2 s.  co  m*/
 */
@SuppressWarnings("all")
public String marshal(final ClassLoader loader, final boolean emitJSON, final Schema schema,
        final Object... objects) throws IllegalArgumentException {

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

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

    // Create the JAXB Marshaller
    Marshaller marshaller = null;
    try {

        marshaller = jaxbContext.createMarshaller();

        // Should we validate the output using the supplied Schema?
        if (schema != null) {
            marshaller.setSchema(schema);
        }

    } catch (Exception e) {
        throw new IllegalStateException("Could not create 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_WRAPPER_AS_ARRAY_NAME, Boolean.TRUE);
            marshaller.setProperty(ECLIPSELINK_JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE);
        } catch (PropertyException e) {
            // This is likely not the EclipseLink Marshaller.
        }
    }

    // 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();
}

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[])//from w  w w. j  a va 2 s  .  co 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();
}

From source file:sernet.verinice.service.XmlRightsService.java

/**
 * Updates the configuration defined in <code>auth</code>.
 * //from   w w  w. j a  va  2  s .  co  m
 * Content of <code>authNew</code> is saved in file: verinice-auth.xml
 * if origin of profiles and userprofiles is "modification".
 * 
 * Before writing the content the implementation checks
 * if user is allowed to change the configuration.
 * 
 * @see sernet.verinice.interfaces.IRightsService#updateConfiguration(sernet.verinice.model.auth.Auth)
 */
@Override
public void updateConfiguration(Auth authNew) {
    try {
        if (!isReferenced(ActionRightIDs.EDITPROFILE, authNew)) {
            log.warn("Right id: " + ActionRightIDs.EDITPROFILE
                    + " is not referenced in the auth configuration. No user is able to change the configuration anymore.");
        }

        Profiles profilesMod = new Profiles();
        for (Profile profile : authNew.getProfiles().getProfile()) {
            // add profile if origin is "modification"
            if (!OriginType.DEFAULT.equals(profile.getOrigin())) {
                profilesMod.getProfile().add(profile);
            }
        }
        authNew.setProfiles(profilesMod);

        Userprofiles userprofilesMod = new Userprofiles();

        for (Userprofile userprofile : authNew.getUserprofiles().getUserprofile()) {
            if (!OriginType.DEFAULT.equals(userprofile.getOrigin())) {
                userprofilesMod.getUserprofile().add(userprofile);
            }
        }
        authNew.setUserprofiles(userprofilesMod);

        // Block all other threads before writing the file
        writeLock.lock();
        try {
            checkWritePermission(); //throws sernet.gs.service.SecurityException
            // create a backup of the old configuration
            backupConfigurationFile();
            // write the new configuration
            Marshaller marshaller = getContext().createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            marshaller.setSchema(getSchema());
            marshaller.marshal(authNew, new FileOutputStream(getAuthConfiguration().getFile().getPath()));
            // set auth to null, 
            // next call of getCofiguration will read the new configuration from disk
            this.auth = null;
        } finally {
            writeLock.unlock();
        }

        fireChangeEvent();

    } catch (sernet.gs.service.SecurityException e) {
        log.error(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        String message = "Error while updating authorization configuration.";
        log.error(message, e);
        // Big Problem: writing of configuration failed! 
        // Restore it from backup
        // Block all other threads before writing the file
        writeLock.lock();
        try {
            log.error("Trying to restore the authorization configuration from backup file now...");
            restoreConfigurationFile();
            log.error("Authorization configuration restored from backup file.");
        } finally {
            writeLock.unlock();
        }
        throw new RuntimeException(message);
    }
}