Java Code Examples for javax.xml.bind.Marshaller#setEventHandler()

The following examples show how to use javax.xml.bind.Marshaller#setEventHandler() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Jaxb2Marshaller.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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}.
 */
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);
	}
}
 
Example 2
Source File: Jaxb2Marshaller.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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}.
 */
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);
	}
}
 
Example 3
Source File: JaxbUtils.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
/**
	 * Marshal object to stream.
	 * 
	 * FIXME
	 * This method support JSON, but the representation does not match the one produced and accepted by Jersey! See {@link ExportParameters}Test
	 * 
	 * @param object
	 * @param out
	 * @param doFormatting
	 * @param type
	 * @param nestedClasses
	 * @return
	 * @throws JAXBException
	 */
	private static <T> ValidationEvent[] marshalToStream(T object, OutputStream out, 
			boolean doFormatting, MarshallerType type, Class<?>... nestedClasses) throws JAXBException {
		ValidationEventCollector vec = new ValidationEventCollector();

		if(type == null) {
			type = MarshallerType.XML;
		}
		final Marshaller marshaller;
		switch(type) {
		case JSON:
			marshaller = createJsonMarshaller(object, doFormatting, nestedClasses);
			break;
		default:
			marshaller = createXmlMarshaller(object, doFormatting, nestedClasses);
			break;
		}
//		marshaller = createXmlMarshaller(object, doFormatting, nestedClasses);
		marshaller.setEventHandler(vec);
		marshaller.marshal(object, out);
		
		checkEvents(vec);
		
		return vec.getEvents();
	}
 
Example 4
Source File: Jaxb2Marshaller.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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 defined properties}, the
 * {@link #setValidationEventHandler validation event handler}, the
 * {@link #setSchemas schemas}, {@link #setMarshallerListener listener},
 * and {@link #setAdapters adapters}.
 */
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);
	}
}
 
Example 5
Source File: SessionSaver.java    From chipster with MIT License 6 votes vote down vote up
/**
 * 
 * @throws JAXBException
 * @throws SAXException
 */
private boolean validateMetadata() throws JAXBException, SAXException {
	Marshaller marshaller = UserSession.getJAXBContext().createMarshaller();
	marshaller.setSchema(UserSession.getSchema());
	marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
	
	NonStoppingValidationEventHandler validationEventHandler = new NonStoppingValidationEventHandler();
	marshaller.setEventHandler(validationEventHandler);
	
	marshaller.marshal(factory.createSession(sessionType), new DefaultHandler());

	if (!validationEventHandler.hasEvents()) {
		 return true;
	} else {
		this.validationErrors = validationEventHandler.getValidationEventsAsString();
		return false;
	}
	 
}
 
Example 6
Source File: TemplateParser.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
@Override
public String getWsagAsSerializedData(String serializedData) throws ParserException {
    StringWriter stringWriter = new StringWriter();
    try {
        Template template = getWsagObject(serializedData);
        JAXBContext jaxbContext = JAXBContext.newInstance(Template.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setEventHandler(new ValidationHandler());
        jaxbMarshaller.marshal(template, stringWriter);
    } catch (JAXBException e) {
        throw new ParserException(e);
    }
    return stringWriter.toString();
}
 
Example 7
Source File: KyeroUtils.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link Marshaller} to write JAXB objects into XML.
 *
 * @param encoding  encoding of written XML
 * @param formatted if written XML is pretty printed
 * @return created marshaller
 * @throws JAXBException if a problem with JAXB occurred
 */
@SuppressWarnings("Duplicates")
public static Marshaller createMarshaller(String encoding, boolean formatted) throws JAXBException {
    Marshaller m = getContext().createMarshaller();
    m.setProperty(Marshaller.JAXB_ENCODING, encoding);
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted);
    m.setEventHandler(new XmlValidationHandler());
    return m;
}
 
Example 8
Source File: DaftIeUtils.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link Marshaller} to write JAXB objects into XML.
 *
 * @param encoding  encoding of written XML
 * @param formatted if written XML is pretty printed
 * @return created marshaller
 * @throws JAXBException if a problem with JAXB occurred
 */
@SuppressWarnings("Duplicates")
public static Marshaller createMarshaller(String encoding, boolean formatted) throws JAXBException {
    Marshaller m = getContext().createMarshaller();
    m.setProperty(Marshaller.JAXB_ENCODING, encoding);
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted);
    m.setEventHandler(new XmlValidationHandler());
    return m;
}
 
Example 9
Source File: SessionSaver.java    From chipster with MIT License 5 votes vote down vote up
private void writeSessionContents(boolean saveData, OutputStream out) throws Exception {

		ZipOutputStream zipOutputStream = null;
		try {	
			zipOutputStream = new ZipOutputStream(new BufferedOutputStream(out));
			zipOutputStream.setLevel(1); // quite slow with bigger values														

			// save meta data
			ZipEntry sessionDataZipEntry = new ZipEntry(UserSession.SESSION_DATA_FILENAME);
			zipOutputStream.putNextEntry(sessionDataZipEntry);
			Marshaller marshaller = UserSession.getJAXBContext().createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			// TODO disable validation
			marshaller.setEventHandler(new NonStoppingValidationEventHandler());
			marshaller.marshal(factory.createSession(sessionType), zipOutputStream);
			zipOutputStream.closeEntry();							

			// save data bean contents
			if (saveData) {
				writeDataBeanContentsToZipFile(zipOutputStream);
			}
			
			// save source codes
			writeSourceCodesToZip(zipOutputStream);
			
			// close the zip stream
			zipOutputStream.close();
		} 
		
		catch (Exception e) {
			IOUtils.closeIfPossible(zipOutputStream);
			throw e;
		}
	}
 
Example 10
Source File: AgreementParser.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
@Override
public String getWsagAsSerializedData(String serializedData) throws ParserException {
    StringWriter stringWriter = new StringWriter();
    try {
        Agreement agreement = getWsagObject(serializedData);
        JAXBContext jaxbContext = JAXBContext.newInstance(Agreement.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setEventHandler(new ValidationHandler());
        jaxbMarshaller.marshal(agreement, stringWriter);
    } catch (JAXBException e) {
        throw new ParserException(e);
    }
    return stringWriter.toString();
}
 
Example 11
Source File: AbstractJAXBProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void validateObjectIfNeeded(Marshaller marshaller, Class<?> cls, Object obj)
    throws JAXBException {
    if (validateOutputIfPossible) {
        Schema theSchema = getSchema(cls);
        if (theSchema != null) {
            marshaller.setEventHandler(eventHandler);
            marshaller.setSchema(theSchema);
            if (validateBeforeWrite) {
                marshaller.marshal(obj, new DefaultHandler());
                marshaller.setSchema(null);
            }
        }
    }
}
 
Example 12
Source File: CasaItUtils.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link Marshaller} to write JAXB objects into XML.
 *
 * @param encoding  encoding of written XML
 * @param formatted if written XML is pretty printed
 * @return created marshaller
 * @throws JAXBException if a problem with JAXB occurred
 */
@SuppressWarnings("Duplicates")
public static Marshaller createMarshaller(String encoding, boolean formatted) throws JAXBException {
    Marshaller m = getContext().createMarshaller();
    m.setProperty(Marshaller.JAXB_ENCODING, encoding);
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted);
    m.setEventHandler(new XmlValidationHandler());
    return m;
}
 
Example 13
Source File: Is24XmlUtils.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link Marshaller} to write JAXB objects into XML.
 *
 * @param encoding  encoding of written XML
 * @param formatted if written XML is pretty printed
 * @return created marshaller
 * @throws JAXBException if a problem with JAXB occurred
 */
@SuppressWarnings("Duplicates")
public static Marshaller createMarshaller(String encoding, boolean formatted) throws JAXBException {
    Marshaller m = getContext().createMarshaller();
    m.setProperty(Marshaller.JAXB_ENCODING, encoding);
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted);
    m.setEventHandler(new XmlValidationHandler());
    return m;
}
 
Example 14
Source File: PageXmlUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
private static Marshaller createMarshaller(ValidationEventCollector vec) throws JAXBException {
	JAXBContext jc = createPageJAXBContext();
	Marshaller m = jc.createMarshaller();
	m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
	m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
	m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocStr);
	m.setEventHandler(vec);
	m.setListener(new TrpPageMarshalListener());
	
	return m;
}
 
Example 15
Source File: IMFCPLSerializer.java    From photon with Apache License 2.0 5 votes vote down vote up
/**
 * A method that serializes the CompositionPlaylistType root element to an XML file
 *
 * @param cplType the composition playlist object
 * @param output stream to which the resulting serialized XML document is written to
 * @param formatted a boolean to indicate if the serialized XML should be formatted (good idea to have it set to true always)
 * @throws IOException - any I/O related error will be exposed through an IOException
 * @throws org.xml.sax.SAXException - any issues with instantiating a schema object with the schema sources will be exposed
 * through a SAXException
 * @throws javax.xml.bind.JAXBException - any issues in serializing the XML document using JAXB will be exposed through a JAXBException
 */

public void write(CompositionPlaylistType cplType, OutputStream output, boolean formatted) throws IOException, org.xml.sax.SAXException, JAXBException {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    try(
            InputStream cplSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_3_2013/imf-cpl.xsd");
            InputStream dcmlSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st0433_2008/dcmlTypes/dcmlTypes.xsd");
            InputStream dsigSchemaAsAStream = contextClassLoader.getResourceAsStream("org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd");
            InputStream coreConstraintsSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_2_2013/imf-core-constraints-20130620-pal.xsd")
    )
    {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI );
        StreamSource[] schemaSources = new StreamSource[4];
        schemaSources[0] = new StreamSource(dsigSchemaAsAStream);
        schemaSources[1] = new StreamSource(dcmlSchemaAsAStream);
        schemaSources[2] = new StreamSource(cplSchemaAsAStream);
        schemaSources[3] = new StreamSource(coreConstraintsSchemaAsAStream);
        Schema schema = schemaFactory.newSchema(schemaSources);

        JAXBContext jaxbContext = JAXBContext.newInstance("org.smpte_ra.schemas.st2067_2_2013");
        Marshaller marshaller = jaxbContext.createMarshaller();
        ValidationEventHandlerImpl validationEventHandler = new ValidationEventHandlerImpl(true);
        marshaller.setEventHandler(validationEventHandler);
        marshaller.setSchema(schema);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted);

        /*marshaller.marshal(cplType, output);
        workaround for 'Error: unable to marshal type "CompositionPlaylistType" as an element because it is missing an @XmlRootElement annotation'
        as found at https://weblogs.java.net/blog/2006/03/03/why-does-jaxb-put-xmlrootelement-sometimes-not-always
         */
        marshaller.marshal(new JAXBElement<>(new QName("http://www.smpte-ra.org/schemas/2067-3/2013", "CompositionPlaylist"), CompositionPlaylistType.class, cplType), output);


        if(validationEventHandler.hasErrors())
        {
            throw new IOException(validationEventHandler.toString());
        }
    }
}
 
Example 16
Source File: XmlTransformer.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
public void toXML( final Object obj, final OutputStream out, final Marshaller.Listener listener ) {
	Marshaller marshaller = null;
	try {
		final JAXBContext jc = createJAXBContext( additionalClazzes );
		marshaller = jc.createMarshaller();
		marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
		marshaller.setProperty( MarshallerProperties.NAMESPACE_PREFIX_MAPPER,
				new MapNamespacePrefixMapper( NAMESPACE_MAPPINGS ) );
		marshaller.setProperty( MarshallerProperties.INDENT_STRING, "\t" );
		marshaller.setEventHandler( new DefaultValidationEventHandler() );
		marshaller.setListener( listener );
		final SessionLogDelegate sessionLog = new SessionLogDelegate( AbstractSessionLog.getLog() );
		AbstractSessionLog.setLog( sessionLog );

		if ( config.isOnlyFragment() ) {
			log.info( "Create only fragment for '{}'.", obj );
			marshaller.setProperty( Marshaller.JAXB_FRAGMENT, true );
		}

		if ( config.isLightweightXml() ) {
			log.info( "Use lightweight XML for '{}'.", obj );
			lightweightMarshallerSet.add( marshaller );
			XmlUtil.addLightWeightAdapter( marshaller );
		}

		marshaller.marshal( obj, out );

		if ( sessionLog.containsMessages() ) {
			throw new RuntimeException( "Error persisting XML: " + sessionLog.getLog() );
		}
	} catch ( final JAXBException e ) {
		throw new RuntimeException( e );
	} finally {
		if ( config.isLightweightXml() && marshaller != null ) {
			lightweightMarshallerSet.remove( marshaller );
		}
	}
}
 
Example 17
Source File: PackingListBuilder.java    From photon with Apache License 2.0 4 votes vote down vote up
/**
 * A method to build a PackingList document compliant with the st0429-8:2007 schema
 * @param annotationText a free form human readable text
 * @param issuer a free form human readable text describing the issuer of the PackingList document
 * @param creator a free form human readable text describing the tool used to create the AssetMap document
 * @param assets a list of PackingListBuilder assets roughly modeling the PackingList Asset compliant
 *               with the st0429-8:2007 schema
 * @return a list of errors that occurred while generating the PackingList document compliant with the st0429-8:2007 schema
 * @throws IOException - any I/O related error will be exposed through an IOException
 */
public List<ErrorLogger.ErrorObject> buildPackingList_2007(@Nonnull org.smpte_ra.schemas.st0429_8_2007.PKL.UserText annotationText,
                                                           @Nonnull org.smpte_ra.schemas.st0429_8_2007.PKL.UserText issuer,
                                                           @Nonnull org.smpte_ra.schemas.st0429_8_2007.PKL.UserText creator,
                                                           @Nonnull List<PackingListBuilderAsset_2007> assets)
        throws IOException {

    IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl();
    org.smpte_ra.schemas.st0429_8_2007.PKL.PackingListType packingListType = IMFPKLObjectFieldsFactory.constructPackingListType_2007();
    packingListType.setId(UUIDHelper.fromUUID(this.uuid));
    packingListType.setAnnotationText(annotationText);
    packingListType.setIconId(this.iconId);
    packingListType.setIssueDate(this.issueDate);
    packingListType.setIssuer(issuer);
    packingListType.setCreator(creator);
    packingListType.setGroupId(this.groupId);
    org.smpte_ra.schemas.st0429_8_2007.PKL.PackingListType.AssetList assetList = new org.smpte_ra.schemas.st0429_8_2007.PKL.PackingListType.AssetList();
    List<org.smpte_ra.schemas.st0429_8_2007.PKL.AssetType> packingListAssets = assetList.getAsset();
    for(PackingListBuilderAsset_2007 asset : assets){
        org.smpte_ra.schemas.st0429_8_2007.PKL.AssetType packingListAssetType = new org.smpte_ra.schemas.st0429_8_2007.PKL.AssetType();
        packingListAssetType.setId(asset.getUUID());
        packingListAssetType.setAnnotationText(asset.getAnnotationText());
        packingListAssetType.setHash(asset.getHash());
        packingListAssetType.setSize(asset.getSize());
        packingListAssetType.setType(asset.getAssetType().toString());
        packingListAssetType.setOriginalFileName(asset.getOriginalFileName());
        packingListAssets.add(packingListAssetType);
    }
    packingListType.setAssetList(assetList);
    //The following attributes are optional setting them to null so that the JAXB Marshaller will not marshall them
    packingListType.setSigner(null);
    packingListType.setSignature(null);


    File outputFile = new File(this.workingDirectory + File.separator + this.pklFileName);
    boolean formatted = true;
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    try(
            InputStream packingListSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st0429_8_2007/PKL/packingList_schema.xsd");
            InputStream dsigSchemaAsAStream = contextClassLoader.getResourceAsStream("org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd");
            OutputStream outputStream = new FileOutputStream(outputFile);
    )
    {
        try
        {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            StreamSource[] schemaSources = new StreamSource[2];
            //The order in which these schema sources are initialized is important because some elements in the
            //PackingList schema depend on types defined in the DSig schema.
            schemaSources[0] = new StreamSource(dsigSchemaAsAStream);
            schemaSources[1] = new StreamSource(packingListSchemaAsAStream);
            Schema schema = schemaFactory.newSchema(schemaSources);

            JAXBContext jaxbContext = JAXBContext.newInstance("org.smpte_ra.schemas.st0429_8_2007.PKL");
            Marshaller marshaller = jaxbContext.createMarshaller();
            ValidationEventHandlerImpl validationEventHandler = new ValidationEventHandlerImpl(true);
            marshaller.setEventHandler(validationEventHandler);
            marshaller.setSchema(schema);
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted);

            /*marshaller.marshal(cplType, output);
            workaround for 'Error: unable to marshal type "AssetMapType" as an element because it is missing an @XmlRootElement annotation'
            as found at https://weblogs.java.net/blog/2006/03/03/why-does-jaxb-put-xmlrootelement-sometimes-not-always
             */
            marshaller.marshal(new JAXBElement<>(new QName("http://www.smpte-ra.org/schemas/429-8/2007/PKL", "PackingList"), org.smpte_ra.schemas.st0429_8_2007.PKL.PackingListType.class, packingListType), outputStream);
            outputStream.close();

            if (validationEventHandler.hasErrors()) {
                //TODO : Perhaps a candidate for a Lambda
                for (ValidationEventHandlerImpl.ValidationErrorObject validationErrorObject : validationEventHandler.getErrors()) {
                    imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, validationErrorObject.getValidationEventSeverity(), validationErrorObject.getErrorMessage());
                }
            }
        }
        catch( SAXException | JAXBException e)
        {
            imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors
                            .ErrorLevels.FATAL,
                    e.getMessage());
        }
    }

    return imfErrorLogger.getErrors();
}
 
Example 18
Source File: PackingListBuilder.java    From photon with Apache License 2.0 4 votes vote down vote up
/**
 * A method to build a PackingList document compliant with the st0429-8:2007 schema
 * @param annotationText a free form human readable text
 * @param issuer a free form human readable text describing the issuer of the PackingList document
 * @param creator a free form human readable text describing the tool used to create the AssetMap document
 * @param assets a list of PackingListBuilder assets roughly modeling the PackingList Asset compliant
 *               with the st0429-8:2007 schema
 * @return a list of errors that occurred while generating the PackingList document compliant with the st0429-8:2007 schema
 * @throws IOException - any I/O related error will be exposed through an IOException
 * @throws SAXException - exposes any issues with instantiating a {@link javax.xml.validation.Schema Schema} object
 * @throws JAXBException - any issues in serializing the XML document using JAXB are exposed through a JAXBException
 */
public List<ErrorLogger.ErrorObject> buildPackingList_2016(@Nonnull org.smpte_ra.schemas.st2067_2_2016.PKL.UserText annotationText,
                                                     @Nonnull org.smpte_ra.schemas.st2067_2_2016.PKL.UserText issuer,
                                                     @Nonnull org.smpte_ra.schemas.st2067_2_2016.PKL.UserText creator,
                                                     @Nonnull List<PackingListBuilderAsset_2016> assets) throws IOException, SAXException, JAXBException {

    int numErrors = imfErrorLogger.getNumberOfErrors();
    org.smpte_ra.schemas.st2067_2_2016.PKL.PackingListType packingListType = IMFPKLObjectFieldsFactory.constructPackingListType_2016();
    packingListType.setId(UUIDHelper.fromUUID(this.uuid));
    packingListType.setIconId(this.iconId);
    packingListType.setAnnotationText(annotationText);
    packingListType.setIssueDate(this.issueDate);
    packingListType.setIssuer(issuer);
    packingListType.setCreator(creator);
    packingListType.setGroupId(this.groupId);
    org.smpte_ra.schemas.st2067_2_2016.PKL.PackingListType.AssetList assetList = new org.smpte_ra.schemas.st2067_2_2016.PKL.PackingListType.AssetList();
    List<org.smpte_ra.schemas.st2067_2_2016.PKL.AssetType> packingListAssets = assetList.getAsset();
    for(PackingListBuilderAsset_2016 asset : assets){
        org.smpte_ra.schemas.st2067_2_2016.PKL.AssetType packingListAssetType = new org.smpte_ra.schemas.st2067_2_2016.PKL.AssetType();
        packingListAssetType.setId(asset.getUUID());
        packingListAssetType.setAnnotationText(asset.getAnnotationText());
        packingListAssetType.setHash(asset.getHash());
        packingListAssetType.setSize(asset.getSize());
        packingListAssetType.setType(asset.getAssetType().toString());
        packingListAssetType.setOriginalFileName(asset.getOriginalFileName());
        packingListAssetType.setHashAlgorithm(asset.getHashAlgorithm());
        packingListAssets.add(packingListAssetType);
    }
    packingListType.setAssetList(assetList);

    //The following attributes are optional setting them to null so that the JAXB Marshaller will not marshall them
    packingListType.setSigner(null);
    packingListType.setSignature(null);

    File outputFile = new File(this.workingDirectory + File.separator + this.pklFileName);
    boolean formatted = true;
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    try(
            InputStream packingListSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_2_2016/PKL/packingList_schema.xsd");
            InputStream dsigSchemaAsAStream = contextClassLoader.getResourceAsStream("org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd");
            OutputStream outputStream = new FileOutputStream(outputFile);
    )
    {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI );
        StreamSource[] schemaSources = new StreamSource[2];
        //The order in which these schema sources are initialized is important because some elements in the
        //PackingList schema depend on types defined in the DSig schema.
        schemaSources[0] = new StreamSource(dsigSchemaAsAStream);
        schemaSources[1] = new StreamSource(packingListSchemaAsAStream);
        Schema schema = schemaFactory.newSchema(schemaSources);

        JAXBContext jaxbContext = JAXBContext.newInstance("org.smpte_ra.schemas.st2067_2_2016.PKL");
        Marshaller marshaller = jaxbContext.createMarshaller();
        ValidationEventHandlerImpl validationEventHandler = new ValidationEventHandlerImpl(true);
        marshaller.setEventHandler(validationEventHandler);
        marshaller.setSchema(schema);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted);

        /*marshaller.marshal(cplType, output);
        workaround for 'Error: unable to marshal type "AssetMapType" as an element because it is missing an @XmlRootElement annotation'
        as found at https://weblogs.java.net/blog/2006/03/03/why-does-jaxb-put-xmlrootelement-sometimes-not-always
         */
        marshaller.marshal(new JAXBElement<>(new QName("http://www.smpte-ra.org/schemas/2067-2/2016/PKL", "PackingList"), org.smpte_ra.schemas.st2067_2_2016.PKL.PackingListType.class, packingListType), outputStream);
        outputStream.close();

        if(validationEventHandler.hasErrors())
        {
            //TODO : Perhaps a candidate for a Lambda
            for(ValidationEventHandlerImpl.ValidationErrorObject validationErrorObject : validationEventHandler.getErrors()) {
                this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, validationErrorObject.getValidationEventSeverity(), validationErrorObject.getErrorMessage());
            }
        }
    }

    if(this.imfErrorLogger.getNumberOfErrors() > numErrors){
        List<ErrorLogger.ErrorObject> fatalErrors = imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, this.imfErrorLogger.getNumberOfErrors());
        if(fatalErrors.size() > 0){
            throw new IMFAuthoringException(String.format("Following FATAL errors were detected while building the PackingList document %s", fatalErrors.toString()));
        }
    }

    return imfErrorLogger.getErrors();
}
 
Example 19
Source File: GenericJAXBMarshaller.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
/**
 * @param aClassLoader
 *        The class loader to be used for XML schema resolving. May be
 *        <code>null</code>.
 * @return A marshaller for converting document to XML. Never
 *         <code>null</code>.
 * @throws JAXBException
 *         In case of an error.
 */
@Nonnull
private Marshaller _createMarshaller (@Nullable final ClassLoader aClassLoader) throws JAXBException
{
  final JAXBContext aJAXBContext = getJAXBContext (aClassLoader);

  // create an Unmarshaller
  final Marshaller aMarshaller = aJAXBContext.createMarshaller ();
  if (m_aVEHFactory != null)
  {
    // Create and set the event handler
    final ValidationEventHandler aEvHdl = m_aVEHFactory.apply (aMarshaller.getEventHandler ());
    if (aEvHdl != null)
      aMarshaller.setEventHandler (aEvHdl);
  }

  if (m_aNSContext != null)
    try
    {
      JAXBMarshallerHelper.setSunNamespacePrefixMapper (aMarshaller, m_aNSContext);
    }
    catch (final Exception ex)
    {
      // Might be an IllegalArgumentException or a NoClassDefFoundError
      LOGGER.error ("Failed to set the namespace context " +
                    m_aNSContext +
                    ": " +
                    ex.getClass ().getName () +
                    " -- " +
                    ex.getMessage (),
                    GlobalDebug.isDebugMode () ? ex.getCause () : null);
    }

  JAXBMarshallerHelper.setFormattedOutput (aMarshaller, m_bFormattedOutput);

  if (m_aCharset != null)
    JAXBMarshallerHelper.setEncoding (aMarshaller, m_aCharset);

  if (m_sIndentString != null)
    JAXBMarshallerHelper.setSunIndentString (aMarshaller, m_sIndentString);

  if (m_sSchemaLocation != null)
    JAXBMarshallerHelper.setSchemaLocation (aMarshaller, m_sSchemaLocation);

  if (m_sNoNamespaceSchemaLocation != null)
    JAXBMarshallerHelper.setNoNamespaceSchemaLocation (aMarshaller, m_sNoNamespaceSchemaLocation);

  // Set XSD (if any)
  final Schema aValidationSchema = createValidationSchema ();
  if (aValidationSchema != null)
    aMarshaller.setSchema (aValidationSchema);

  return aMarshaller;
}
 
Example 20
Source File: ImmobiliareItUtils.java    From OpenEstate-IO with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a {@link Marshaller} to write JAXB objects into XML.
 *
 * @param encoding  encoding of written XML
 * @param formatted if written XML is pretty printed
 * @return created marshaller
 * @throws JAXBException if a problem with JAXB occurred
 */
public static Marshaller createMarshaller(String encoding, boolean formatted) throws JAXBException {
    Marshaller m = getContext().createMarshaller();
    m.setProperty(Marshaller.JAXB_ENCODING, encoding);
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted);
    m.setEventHandler(new XmlValidationHandler());
    return m;
}