Java Code Examples for javax.xml.bind.Marshaller#setSchema()
The following examples show how to use
javax.xml.bind.Marshaller#setSchema() .
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: ConverterImpl.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 7 votes |
@Override public String toXML(T obj) { try { JAXBContext context = JAXBContext.newInstance(type); Marshaller m = context.createMarshaller(); if(schemaLocation != null) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); StreamSource source = new StreamSource(getClass().getResourceAsStream(schemaLocation)); Schema schema = schemaFactory.newSchema(source); m.setSchema(schema); } StringWriter writer = new StringWriter(); m.marshal(obj, writer); String xml = writer.toString(); return xml; } catch (Exception e) { System.out.println("ERROR: "+e.toString()); return null; } }
Example 2
Source File: Jaxb2Marshaller.java From java-technology-stack with MIT License | 6 votes |
/** * 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: XmlMultiConfiguration.java From ehcache3 with Apache License 2.0 | 6 votes |
private XmlMultiConfiguration(Map<String, Config> configurations) { try { Schema schema = discoverSchema(new StreamSource(CORE_SCHEMA_URL.openStream()), new StreamSource(MULTI_SCHEMA_URL.openStream())); this.configurations = configurations; ObjectFactory objectFactory = new ObjectFactory(); Configurations jaxb = objectFactory.createConfigurations().withConfiguration(configurations.entrySet().stream().map( entry -> entry.getValue().unparse(objectFactory, objectFactory.createConfigurationsConfiguration().withIdentity(entry.getKey()))).collect(toList())); JAXBContext jaxbContext = JAXBContext.newInstance(Configurations.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setSchema(schema); this.document = documentBuilder(schema).newDocument(); marshaller.marshal(jaxb, document); this.renderedDocument = documentToText(document); } catch (JAXBException | IOException | TransformerException | ParserConfigurationException | SAXException e) { throw new XmlConfigurationException(e); } }
Example 4
Source File: ConversionService.java From validator with Apache License 2.0 | 6 votes |
public <T> String writeXml(final T model, final Schema schema, final ValidationEventHandler handler) { if (model == null) { throw new ConversionExeption("Can not serialize null"); } try ( final StringWriter w = new StringWriter() ) { final JAXBIntrospector introspector = getJaxbContext().createJAXBIntrospector(); final Marshaller marshaller = getJaxbContext().createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.setSchema(schema); marshaller.setEventHandler(handler); final XMLOutputFactory xof = XMLOutputFactory.newFactory(); final XMLStreamWriter xmlStreamWriter = xof.createXMLStreamWriter(w); if (null == introspector.getElementName(model)) { final JAXBElement jaxbElement = new JAXBElement(createQName(model), model.getClass(), model); marshaller.marshal(jaxbElement, xmlStreamWriter); } else { marshaller.marshal(model, xmlStreamWriter); } xmlStreamWriter.flush(); return w.toString(); } catch (final JAXBException | IOException | XMLStreamException e) { throw new ConversionExeption(String.format("Error serializing Object %s", model.getClass().getName()), e); } }
Example 5
Source File: TrustedListSigningTest.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
@SuppressWarnings("unchecked") private void unmarshallingTester(Document doc) throws JAXBException, SAXException { JAXBContext jc = trustedListUtils.getJAXBContext(); Schema schema = trustedListUtils.getSchema(); Unmarshaller unmarshaller = jc.createUnmarshaller(); unmarshaller.setSchema(schema); JAXBElement<TrustStatusListType> unmarshalled = (JAXBElement<TrustStatusListType>) unmarshaller.unmarshal(doc); assertNotNull(unmarshalled); Marshaller marshaller = jc.createMarshaller(); marshaller.setSchema(schema); StringWriter sw = new StringWriter(); marshaller.marshal(unmarshalled, sw); String tlString = sw.toString(); JAXBElement<TrustStatusListType> unmarshalled2 = (JAXBElement<TrustStatusListType>) unmarshaller.unmarshal(new StringReader(tlString)); assertNotNull(unmarshalled2); }
Example 6
Source File: AbstractJaxbFacade.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
public Marshaller getMarshaller(boolean validate) throws JAXBException, SAXException, IOException { Marshaller marshaller = getJAXBContext().createMarshaller(); if (validate) { marshaller.setSchema(getSchema()); } marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); return marshaller; }
Example 7
Source File: JAXBTest.java From hyperjaxb3 with BSD 2-Clause "Simplified" License | 5 votes |
public void testValidate() throws SAXException, JAXBException { final PurchaseOrderType purchaseOrder = objectFactory .createPurchaseOrderType(); purchaseOrder.setShipTo(objectFactory.createUSAddress()); purchaseOrder.setBillTo(objectFactory.createUSAddress()); final JAXBElement<PurchaseOrderType> purchaseOrderElement = objectFactory .createPurchaseOrder(purchaseOrder); final SchemaFactory schemaFactory = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema = schemaFactory.newSchema(new StreamSource( getClass().getClassLoader().getResourceAsStream("po.xsd"))); final Marshaller marshaller = context.createMarshaller(); marshaller.setSchema(schema); final List<ValidationEvent> events = new LinkedList<ValidationEvent>(); marshaller.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { events.add(event); return true; } }); marshaller.marshal(purchaseOrderElement, new DOMResult()); assertFalse("List of validation events must not be empty.", events .isEmpty()); System.out.println(events.get(0)); }
Example 8
Source File: XmlDSigUtilsTest.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
@Test @SuppressWarnings("unchecked") public void test() throws JAXBException, SAXException { File xmldsigFile = new File("src/test/resources/XmlAliceSig.xml"); JAXBContext jc = xmlDSigUtils.getJAXBContext(); assertNotNull(jc); Schema schema = xmlDSigUtils.getSchema(); assertNotNull(schema); Unmarshaller unmarshaller = jc.createUnmarshaller(); unmarshaller.setSchema(schema); JAXBElement<SignatureType> unmarshalled = (JAXBElement<SignatureType>) unmarshaller.unmarshal(xmldsigFile); assertNotNull(unmarshalled); Marshaller marshaller = jc.createMarshaller(); marshaller.setSchema(schema); StringWriter sw = new StringWriter(); marshaller.marshal(unmarshalled, sw); String xmldsigString = sw.toString(); JAXBElement<SignatureType> unmarshalled2 = (JAXBElement<SignatureType>) unmarshaller.unmarshal(new StringReader(xmldsigString)); assertNotNull(unmarshalled2); }
Example 9
Source File: Generator.java From DataDefender with Apache License 2.0 | 5 votes |
/** * Write requirement to file. * @param requirement * @param outFile * @throws DatabaseException */ public static void write(final Requirement requirement, final File outFile) throws DatabaseException, JAXBException, SAXException { log.info("Requirement.write() to file: " + outFile.getName()); final JAXBContext jc = JAXBContext.newInstance(Requirement.class); final Marshaller marshaller = jc.createMarshaller(); final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema = schemaFactory.newSchema(Generator.class.getResource("requirement.xsd")); marshaller.setSchema(schema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(requirement, outFile); }
Example 10
Source File: JAXBSimpleWriter.java From citygml4j with Apache License 2.0 | 5 votes |
public void write(AbstractFeature abstractFeature) throws CityGMLWriteException { if (featureWriteMode == FeatureWriteMode.SPLIT_PER_COLLECTION_MEMBER && featureSplitter != null) abstractFeature = split(abstractFeature); try { JAXBElement<?> jaxbElement = jaxbMarshaller.marshalJAXBElement(abstractFeature); if (jaxbElement != null) { Marshaller marshaller = jaxbContext.createMarshaller(); // validate output if (useValidation) { marshaller.setSchema(validationSchemaHandler.getSchema()); if (validationEventHandler != null) marshaller.setEventHandler(validationEventHandler); } // marshal output if (transformerChainFactory == null) marshaller.marshal(jaxbElement, writer); else { // apply transformation before marshalling TransformerChain chain = transformerChainFactory.buildChain(); chain.tail().setResult(new SAXResult(writer)); marshaller.marshal(jaxbElement, chain.head()); } writer.flush(); } } catch (JAXBException | SAXException | TransformerConfigurationException e) { throw new CityGMLWriteException("Caused by: ", e); } }
Example 11
Source File: XmlTransformer.java From nomulus with Apache License 2.0 | 5 votes |
/** Get a {@link Marshaller} instance with the given configuration. */ private Marshaller getMarshaller(@Nullable Schema schemaParam, Map<String, ?> properties) throws JAXBException { Marshaller marshaller = jaxbContext.createMarshaller(); for (Map.Entry<String, ?> entry : properties.entrySet()) { marshaller.setProperty(entry.getKey(), entry.getValue()); } marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setSchema(schemaParam); return marshaller; }
Example 12
Source File: ChangeSetMapper.java From pinpoint with Apache License 2.0 | 5 votes |
private Marshaller createMarshaller() throws JAXBException { Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setSchema(schema); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); return marshaller; }
Example 13
Source File: FileUserGroupProvider.java From nifi-registry with Apache License 2.0 | 4 votes |
private void saveTenants(final Tenants tenants) throws JAXBException { final Marshaller marshaller = JAXB_TENANTS_CONTEXT.createMarshaller(); marshaller.setSchema(tenantsSchema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(tenants, tenantsFile); }
Example 14
Source File: FileAccessPolicyProvider.java From nifi-registry with Apache License 2.0 | 4 votes |
private void saveAuthorizations(final Authorizations authorizations) throws JAXBException { final Marshaller marshaller = JAXB_AUTHORIZATIONS_CONTEXT.createMarshaller(); marshaller.setSchema(authorizationsSchema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(authorizations, authorizationsFile); }
Example 15
Source File: FileAccessPolicyProvider.java From nifi with Apache License 2.0 | 4 votes |
private void saveAuthorizations(final Authorizations authorizations, final File destinationFile) throws JAXBException { final Marshaller marshaller = JAXB_AUTHORIZATIONS_CONTEXT.createMarshaller(); marshaller.setSchema(authorizationsSchema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(authorizations, destinationFile); }
Example 16
Source File: CompositionPlaylistBuilder_2013.java From photon with Apache License 2.0 | 4 votes |
private List<ErrorLogger.ErrorObject> serializeCPLToXML(org.smpte_ra.schemas .st2067_2_2013.CompositionPlaylistType cplRoot, File outputFile) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); boolean formatted = true; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); 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"); try(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"); OutputStream outputStream = new FileOutputStream(outputFile);) { try { 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, cplRoot), outputStream); if (validationEventHandler.hasErrors()) { //TODO : Perhaps a candidate for a Lambda for (ValidationEventHandlerImpl.ValidationErrorObject validationErrorObject : validationEventHandler.getErrors()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_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 17
Source File: FileUserGroupProvider.java From nifi with Apache License 2.0 | 4 votes |
private void saveTenants(final Tenants tenants, final File destinationFile) throws JAXBException { final Marshaller marshaller = JAXB_TENANTS_CONTEXT.createMarshaller(); marshaller.setSchema(tenantsSchema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(tenants, destinationFile); }
Example 18
Source File: PackingListBuilder.java From photon with Apache License 2.0 | 4 votes |
/** * 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: FileAuthorizer.java From localization_nifi with Apache License 2.0 | 4 votes |
private void saveTenants(final Tenants tenants) throws JAXBException { final Marshaller marshaller = JAXB_TENANTS_CONTEXT.createMarshaller(); marshaller.setSchema(tenantsSchema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(tenants, tenantsFile); }
Example 20
Source File: JAXBUtil.java From keycloak with Apache License 2.0 | 3 votes |
/** * Get the JAXB Marshaller * * @param pkgName The package name for the jaxb context * @param schemaLocation location of the schema to validate against * * @return Marshaller * * @throws JAXBException * @throws SAXException */ public static Marshaller getValidatingMarshaller(String pkgName, String schemaLocation) throws JAXBException, SAXException { Marshaller marshaller = getMarshaller(pkgName); // Validate against schema Schema schema = getJAXPSchemaInstance(schemaLocation); marshaller.setSchema(schema); return marshaller; }