Java Code Examples for javax.xml.bind.Marshaller

The following are top voted examples for showing how to use javax.xml.bind.Marshaller. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: springboot-training   File: XMLUtil.java   Source Code and License 7 votes vote down vote up
/**
 * 对象转为xml字符串
 * 
 * @param obj
 * @param isFormat
 *            true即按标签自动换行,false即是一行的xml
 * @param includeHead
 *            true则包含xm头声明信息,false则不包含
 * @return
 */
public String obj2xml(Object obj, boolean isFormat, boolean includeHead) {
	try (StringWriter writer = new StringWriter()) {
		Marshaller m = MARSHALLERS.get(obj.getClass());
		if (m == null) {
			m = JAXBContext.newInstance(obj.getClass()).createMarshaller();
			m.setProperty(Marshaller.JAXB_ENCODING, I18NConstants.DEFAULT_CHARSET);
		}
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, isFormat);
		m.setProperty(Marshaller.JAXB_FRAGMENT, !includeHead);// 是否省略xm头声明信息
		m.marshal(obj, writer);
		return writer.toString();
	} catch (Exception e) {
		throw new ZhhrException(e.getMessage(), e);
	}
}
 
Example 2
Project: incubator-netbeans   File: SaasUtil.java   Source Code and License 6 votes vote down vote up
public static void saveSaas(Saas saas, FileObject file) throws IOException, JAXBException {
    JAXBContext jc = JAXBContext.newInstance(SaasServices.class.getPackage().getName());
    Marshaller marshaller = jc.createMarshaller();
    JAXBElement<SaasServices> jbe = new JAXBElement<SaasServices>(QNAME_SAAS_SERVICES, SaasServices.class, saas.getDelegate());
    OutputStream out = null;
    FileLock lock = null;
    try {
        lock = file.lock();
        out = file.getOutputStream(lock);
        marshaller.marshal(jbe, out);
    } finally {
        if (out != null) {
            out.close();
        }
        if (lock != null) {
            lock.releaseLock();
        }
    }
}
 
Example 3
Project: AgentWorkbench   File: ThreadProtocol.java   Source Code and License 6 votes vote down vote up
/**
 * Save.
 *
 * @param file2Save the file2 save
 * @return true, if successful
 */
public boolean save(File file2Save) {
	
	boolean saved = true;
	try {			
		JAXBContext pc = JAXBContext.newInstance(this.getClass()); 
		Marshaller pm = pc.createMarshaller(); 
		pm.setProperty( Marshaller.JAXB_ENCODING, "UTF-8" );
		pm.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); 

		Writer pw = new FileWriter(file2Save);
		pm.marshal(this, pw);
		pw.close();

	} catch (Exception e) {
		System.out.println("XML-Error while saving Setup-File!");
		e.printStackTrace();
		saved = false;
	}		
	return saved;		
}
 
Example 4
Project: JavaRushTasks   File: Solution.java   Source Code and License 6 votes vote down vote up
public static String toXmlWithComment(Object obj, String tagName, String comment) {
    StringWriter writer = new StringWriter();
    String res = null;
    try {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(obj, writer);

        String xml = writer.toString();

        if (xml.indexOf(tagName) > -1)
            res = xml.replace("<" + tagName + ">", "<!--" + comment + "-->\n" + "<" + tagName + ">");
        else
            res = xml;

    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return res;
}
 
Example 5
Project: kanphnia2   File: MainApp.java   Source Code and License 6 votes vote down vote up
public void saveEntryDataToFile(File f) {
	try {
		JAXBContext context = JAXBContext.newInstance(EntryListWrapper.class);
		Marshaller m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		
		// wrapping the entry data
		EntryListWrapper wrapper = new EntryListWrapper();
		wrapper.setEntries(entryList);
		
		// marshalling and saving xml to file
		m.marshal(wrapper, f);
		
		// save file path
		setFilePath(f);
	}
	catch (Exception e) {
		Alert alert = new Alert(AlertType.ERROR);
		alert.setTitle("Error");
		alert.setHeaderText("Could not save data");
		alert.setContentText("Could not save data to file:\n" + f.getPath());
		
		alert.showAndWait();
	}
}
 
Example 6
Project: dss-demonstrations   File: XSLTServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void generateDetailedReportMultiSignatures() throws Exception {
	JAXBContext context = JAXBContext.newInstance(DetailedReport.class.getPackage().getName());
	Unmarshaller unmarshaller = context.createUnmarshaller();
	Marshaller marshaller = context.createMarshaller();

	DetailedReport detailedReport = (DetailedReport) unmarshaller.unmarshal(new File("src/test/resources/detailed-report-multi-signatures.xml"));
	assertNotNull(detailedReport);

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

	String htmlDetailedReport = service.generateDetailedReport(writer.toString());
	assertTrue(Utils.isStringNotEmpty(htmlDetailedReport));
	logger.debug("Detailed report html : " + htmlDetailedReport);
}
 
Example 7
Project: OpenJSharp   File: JAXBSource.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a new {@link javax.xml.transform.Source} for the given content object.
 *
 * @param   marshaller
 *      A marshaller instance that will be used to marshal
 *      <code>contentObject</code> into XML. This must be
 *      created from a JAXBContext that was used to build
 *      <code>contentObject</code> and must not be null.
 * @param   contentObject
 *      An instance of a JAXB-generated class, which will be
 *      used as a {@link javax.xml.transform.Source} (by marshalling it into XML).  It must
 *      not be null.
 * @throws JAXBException if an error is encountered while creating the
 * JAXBSource or if either of the parameters are null.
 */
public JAXBSource( Marshaller marshaller, Object contentObject )
    throws JAXBException {

    if( marshaller == null )
        throw new JAXBException(
            Messages.format( Messages.SOURCE_NULL_MARSHALLER ) );

    if( contentObject == null )
        throw new JAXBException(
            Messages.format( Messages.SOURCE_NULL_CONTENT ) );

    this.marshaller = marshaller;
    this.contentObject = contentObject;

    super.setXMLReader(pseudoParser);
    // pass a dummy InputSource. We don't care
    super.setInputSource(new InputSource());
}
 
Example 8
Project: OpenJSharp   File: JAXBMessage.java   Source Code and License 6 votes vote down vote up
@Override
public XMLStreamReader readPayload() throws XMLStreamException {
   try {
        if(infoset==null) {
                            if (rawContext != null) {
                    XMLStreamBufferResult sbr = new XMLStreamBufferResult();
                                    Marshaller m = rawContext.createMarshaller();
                                    m.setProperty("jaxb.fragment", Boolean.TRUE);
                                    m.marshal(jaxbObject, sbr);
                    infoset = sbr.getXMLStreamBuffer();
                            } else {
                                MutableXMLStreamBuffer buffer = new MutableXMLStreamBuffer();
                                writePayloadTo(buffer.createFromXMLStreamWriter());
                                infoset = buffer;
                            }
        }
        XMLStreamReader reader = infoset.readAsXMLStreamReader();
        if(reader.getEventType()== START_DOCUMENT)
            XMLStreamReaderUtil.nextElementContent(reader);
        return reader;
    } catch (JAXBException e) {
       // bug 6449684, spec 4.3.4
       throw new WebServiceException(e);
    }
}
 
Example 9
Project: OpenJSharp   File: JAXBMessage.java   Source Code and License 6 votes vote down vote up
@Override
public <T> T readPayloadAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
    JAXBResult out = new JAXBResult(unmarshaller);
    // since the bridge only produces fragments, we need to fire start/end document.
    try {
        out.getHandler().startDocument();
        if (rawContext != null) {
            Marshaller m = rawContext.createMarshaller();
            m.setProperty("jaxb.fragment", Boolean.TRUE);
            m.marshal(jaxbObject,out);
        } else
            bridge.marshal(jaxbObject,out);
        out.getHandler().endDocument();
    } catch (SAXException e) {
        throw new JAXBException(e);
    }
    return (T)out.getResult();
}
 
Example 10
Project: OpenJSharp   File: JAXBDispatchMessage.java   Source Code and License 6 votes vote down vote up
private void readPayloadElement() {
    PayloadElementSniffer sniffer = new PayloadElementSniffer();
    try {
        if (rawContext != null) {
            Marshaller m = rawContext.createMarshaller();
            m.setProperty("jaxb.fragment", Boolean.FALSE);
            m.marshal(jaxbObject, sniffer);
        } else {
            bridge.marshal(jaxbObject, sniffer, null);
        }

    } catch (JAXBException e) {
        // if it's due to us aborting the processing after the first element,
        // we can safely ignore this exception.
        //
        // if it's due to error in the object, the same error will be reported
        // when the readHeader() method is used, so we don't have to report
        // an error right now.
        payloadQName = sniffer.getPayloadQName();
    }
}
 
Example 11
Project: util   File: XmlMapper.java   Source Code and License 6 votes vote down vote up
/**
 * 创建Marshaller并设定encoding(可为null). 线程不安全,需要每次创建或pooling。
 */
@SuppressWarnings("rawtypes")
public static Marshaller createMarshaller(Class clazz, String encoding) {
	try {
		JAXBContext jaxbContext = getJaxbContext(clazz);

		Marshaller marshaller = jaxbContext.createMarshaller();

		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

		if (StringUtils.isNotBlank(encoding)) {
			marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
		}

		return marshaller;
	} catch (JAXBException e) {
		throw ExceptionUtil.unchecked(e);
	}
}
 
Example 12
Project: oscm   File: RevenueCalculatorBean.java   Source Code and License 6 votes vote down vote up
private void serializeBillingDetails(BillingResult billingResult,
        BillingDetailsType billingDetails) {

    try {
        final JAXBContext context = JAXBContext
                .newInstance(BillingdataType.class);
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty("jaxb.formatted.output", Boolean.FALSE);
        final BillingdataType billingdataType = new BillingdataType();
        billingdataType.getBillingDetails().add(billingDetails);
        marshaller.marshal(factory.createBillingdata(billingdataType), out);
        final String xml = new String(out.toByteArray(), "UTF-8");
        billingResult.setResultXML(xml.substring(
                xml.indexOf("<Billingdata>") + 13,
                xml.indexOf("</Billingdata>")).trim());
        billingResult.setGrossAmount(billingDetails.getOverallCosts()
                .getGrossAmount());
        billingResult.setNetAmount(billingDetails.getOverallCosts()
                .getNetAmount());
    } catch (JAXBException | UnsupportedEncodingException ex) {
        throw new BillingRunFailed(ex);
    }
}
 
Example 13
Project: nifi-registry   File: JAXBSerializer.java   Source Code and License 6 votes vote down vote up
@Override
public void serialize(final T t, final OutputStream out) throws SerializationException {
    if (t == null) {
        throw new IllegalArgumentException("The object to serialize cannot be null");
    }

    if (out == null) {
        throw new IllegalArgumentException("OutputStream cannot be null");
    }

    try {
        final Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(t, out);
    } catch (JAXBException e) {
        throw new SerializationException("Unable to serialize object", e);
    }
}
 
Example 14
Project: testing_security_development_enterprise_systems   File: ConverterImpl.java   Source Code and License 6 votes vote down vote up
@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 15
Project: Equella   File: LtiServiceImpl.java   Source Code and License 6 votes vote down vote up
private Request createLtiOutcomesRequest(ImsxPOXEnvelopeType imsxEnvelope, String url, String consumerKey,
	String consumerSecret) throws Exception
{
	final Request webRequest = new Request(url);
	webRequest.setMethod(Method.POST);
	webRequest.setMimeType("application/xml");

	final ObjectFactory of = new ObjectFactory();
	final JAXBElement<ImsxPOXEnvelopeType> createImsxPOXEnvelopeRequest = of
		.createImsxPOXEnvelopeRequest(imsxEnvelope);

	final JAXBContext jc = JAXBContext.newInstance("com.tle.web.lti.imsx", LtiServiceImpl.class.getClassLoader());
	final Marshaller marshaller = jc.createMarshaller();
	marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

	final StringWriter sw = new StringWriter();
	marshaller.marshal(createImsxPOXEnvelopeRequest, sw);
	webRequest.setBody(sw.toString());

	final String bodyHash = calcSha1Hash(webRequest.getBody());
	final OAuthMessage message = createLaunchParameters(consumerKey, consumerSecret, url, bodyHash);
	webRequest.addHeader("Authorization", message.getAuthorizationHeader(""));
	return webRequest;
}
 
Example 16
Project: Code-Lib   File: JAXBmarshallerTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {

		  Customer customer = new Customer();
		  customer.setId(100);
		  customer.setName("mkyong");
		  customer.setAge(29);

		  try {

			File file = new File("file.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

			// output pretty printed
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

			jaxbMarshaller.marshal(customer, file);
			jaxbMarshaller.marshal(customer, System.out);

		      } catch (JAXBException e) {
			e.printStackTrace();
		      }

		}
 
Example 17
Project: OpenJSharp   File: OldBridge.java   Source Code and License 5 votes vote down vote up
public final void marshal(T object,XMLStreamWriter output, AttachmentMarshaller am) throws JAXBException {
    Marshaller m = context.marshallerPool.take();
    m.setAttachmentMarshaller(am);
    marshal(m,object,output);
    m.setAttachmentMarshaller(null);
    context.marshallerPool.recycle(m);
}
 
Example 18
Project: OpenJSharp   File: ExceptionBean.java   Source Code and License 5 votes vote down vote up
/**
 * Converts the given {@link Throwable} into an XML representation
 * and put that as a DOM tree under the given node.
 */
public static void marshal( Throwable t, Node parent ) throws JAXBException {
    Marshaller m = JAXB_CONTEXT.createMarshaller();
    try {
            m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper",nsp);
    } catch (PropertyException pe) {}
    m.marshal(new ExceptionBean(t), parent );
}
 
Example 19
Project: OpenJSharp   File: Bridge.java   Source Code and License 5 votes vote down vote up
/**
 * @since 2.0.2
 */
public void marshal(T object,OutputStream output, NamespaceContext nsContext, AttachmentMarshaller am) throws JAXBException {
    Marshaller m = context.marshallerPool.take();
    m.setAttachmentMarshaller(am);
    marshal(m,object,output,nsContext);
    m.setAttachmentMarshaller(null);
    context.marshallerPool.recycle(m);
}
 
Example 20
Project: OpenJSharp   File: BridgeImpl.java   Source Code and License 5 votes vote down vote up
public void marshal(Marshaller _m, T t, OutputStream output, NamespaceContext nsContext) throws JAXBException {
    MarshallerImpl m = (MarshallerImpl)_m;

    Runnable pia = null;
    if(nsContext!=null)
        pia = new StAXPostInitAction(nsContext,m.serializer);

    m.write(tagName,bi,t,m.createWriter(output),pia);
}
 
Example 21
Project: jdk8u-jdk   File: Test.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance("testjaxbcontext");
    Unmarshaller u = jc.createUnmarshaller();
    Object result = u.unmarshal(new File(System.getProperty("test.src", ".") + "/test.xml"));
    StringWriter sw = new StringWriter();
    Marshaller m = jc.createMarshaller();
    m.marshal(result, sw);
    System.out.println("Expected:" + EXPECTED);
    System.out.println("Observed:" + sw.toString());
    if (!EXPECTED.equals(sw.toString())) {
        throw new Exception("Unmarshal/Marshal generates different content");
    }
}
 
Example 22
Project: elastic-db-tools-for-java   File: SqlStoreTransactionScope.java   Source Code and License 5 votes vote down vote up
/**
 * Convert StoreOperationInput XML to string.
 *
 * @param jaxbContext
 *            JAXBContext
 * @param o
 *            StoreOperationInput
 * @return StoreOperationInput as String
 * @throws JAXBException
 *             Exception if unable to convert
 */
public static String asString(JAXBContext jaxbContext,
        Object o) throws JAXBException {

    java.io.StringWriter sw = new StringWriter();

    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    marshaller.marshal(o, sw);

    return sw.toString();
}
 
Example 23
Project: XXXX   File: JAXBContextFactoryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void buildsMarshallerWithFragmentProperty() throws Exception {
  JAXBContextFactory
      factory =
      new JAXBContextFactory.Builder().withMarshallerFragment(true).build();

  Marshaller marshaller = factory.createMarshaller(Object.class);
  assertTrue((Boolean) marshaller.getProperty(Marshaller.JAXB_FRAGMENT));
}
 
Example 24
Project: OpenJSharp   File: W3CEndpointReference.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void writeTo(Result result){
    try {
        Marshaller marshaller = w3cjc.createMarshaller();
        marshaller.marshal(this, result);
    } catch (JAXBException e) {
        throw new WebServiceException("Error marshalling W3CEndpointReference. ", e);
    }
}
 
Example 25
Project: openjdk-jdk10   File: MemberSubmissionEndpointReference.java   Source Code and License 5 votes vote down vote up
@Override
public void writeTo(Result result) {
    try {
        Marshaller marshaller = MemberSubmissionEndpointReference.msjc.get().createMarshaller();
        //marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.marshal(this, result);
    } catch (JAXBException e) {
        throw new WebServiceException("Error marshalling W3CEndpointReference. ", e);
    }
}
 
Example 26
Project: dss-demonstrations   File: FOPServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void generateSimpleReport() throws Exception {
	JAXBContext context = JAXBContext.newInstance(SimpleReport.class.getPackage().getName());
	Unmarshaller unmarshaller = context.createUnmarshaller();
	Marshaller marshaller = context.createMarshaller();

	SimpleReport simpleReport = (SimpleReport) unmarshaller.unmarshal(new File("src/test/resources/simpleReport.xml"));
	assertNotNull(simpleReport);

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

	FileOutputStream fos = new FileOutputStream("target/simpleReport.pdf");
	service.generateSimpleReport(writer.toString(), fos);
}
 
Example 27
Project: dss-demonstrations   File: FOPServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void generateDetailedReportMultiSignatures() throws Exception {
	JAXBContext context = JAXBContext.newInstance(DetailedReport.class.getPackage().getName());
	Unmarshaller unmarshaller = context.createUnmarshaller();
	Marshaller marshaller = context.createMarshaller();

	DetailedReport detailedReport = (DetailedReport) unmarshaller.unmarshal(new File("src/test/resources/detailed-report-multi-signatures.xml"));
	assertNotNull(detailedReport);

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

	FileOutputStream fos = new FileOutputStream("target/detailedReportMulti.pdf");
	service.generateDetailedReport(writer.toString(), fos);
}
 
Example 28
Project: OpenJSharp   File: XMLSerializer.java   Source Code and License 5 votes vote down vote up
/**
 * Invoke the beforeMarshal api on the external listener (if it exists) and on the bean embedded
 * beforeMarshal api(if it exists).
 *
 * This method is called only after the callee has determined that beanInfo.lookForLifecycleMethods == true.
 *
 * @param beanInfo
 * @param currentTarget
 */
private void fireBeforeMarshalEvents(final JaxBeanInfo beanInfo, Object currentTarget) {
    // first invoke bean embedded listener
    if (beanInfo.hasBeforeMarshalMethod()) {
        Method m = beanInfo.getLifecycleMethods().beforeMarshal;
        fireMarshalEvent(currentTarget, m);
    }

    // then invoke external listener
    Marshaller.Listener externalListener = marshaller.getListener();
    if (externalListener != null) {
        externalListener.beforeMarshal(currentTarget);
    }
}
 
Example 29
Project: openjdk-jdk10   File: OldBridge.java   Source Code and License 5 votes vote down vote up
/**
 * @since 2.0.2
 */
public void marshal(T object,OutputStream output, NamespaceContext nsContext, AttachmentMarshaller am) throws JAXBException {
    Marshaller m = context.marshallerPool.take();
    m.setAttachmentMarshaller(am);
    marshal(m,object,output,nsContext);
    m.setAttachmentMarshaller(null);
    context.marshallerPool.recycle(m);
}
 
Example 30
Project: DIA-Umpire-Maven   File: TraMLParser.java   Source Code and License 5 votes vote down vote up
public void writeToFile(String filename) throws Exception {

        JAXBContext ctx = JAXBContext.newInstance("ExternalPackages.org.hupo.psi.ms.traml");
        Marshaller m = ctx.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, JTRAML_URL.TRAML_XSD_LOCATION);
        m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

        JAXBElement<TraMLType> tramlWrap =
                new JAXBElement<TraMLType>(new QName(JTRAML_URL.TRAML_URI, "TraML"), TraMLType.class, traML);

        m.marshal(tramlWrap, new FileWriter(filename));
    }
 
Example 31
Project: family-tree-xml-parser   File: DocumentControllerTest.java   Source Code and License 5 votes vote down vote up
private String getRequestBody(Entries entries) throws JAXBException {
  JAXBContext context = JAXBContext.newInstance(Entries.class);
  Marshaller marshaller = context.createMarshaller();
  StringWriter stringWriter = new StringWriter();
  marshaller.marshal(entries, stringWriter);
  return stringWriter.toString();
}
 
Example 32
Project: school-game   File: DialogDataHelper.java   Source Code and License 5 votes vote down vote up
public static void saveDialogRoot(File dialogFile, Level root) throws JAXBException, SAXException
{

    Marshaller marshaller = getJaxbContext().createMarshaller();
    marshaller.setSchema(getSchema());
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    marshaller.marshal(root, dialogFile);
}
 
Example 33
Project: openjdk-jdk10   File: BridgeImpl.java   Source Code and License 5 votes vote down vote up
public void marshal(Marshaller _m, T t, OutputStream output, NamespaceContext nsContext) throws JAXBException {
    MarshallerImpl m = (MarshallerImpl)_m;

    Runnable pia = null;
    if(nsContext!=null)
        pia = new StAXPostInitAction(nsContext,m.serializer);

    m.write(tagName,bi,t,m.createWriter(output),pia);
}
 
Example 34
Project: DocIT   File: Serialization.java   Source Code and License 5 votes vote down vote up
public static void writeCompany(File output, Company c)
throws 	JAXBException,
		FileNotFoundException,
		XMLStreamException 
{
	initializeJaxbContext();
    OutputStream os = new FileOutputStream(output);
	Marshaller marshaller = jaxbContext.createMarshaller();
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
       XMLStreamWriter writer = outputFactory.createXMLStreamWriter(os);
	marshaller.marshal(c, writer); // TODO: need a stream writer that does indentation		
}
 
Example 35
Project: openjdk-jdk10   File: OldBridge.java   Source Code and License 5 votes vote down vote up
/**
 * @since 2.0.2
 */
public final void marshal(T object, ContentHandler contentHandler, AttachmentMarshaller am) throws JAXBException {
    Marshaller m = context.marshallerPool.take();
    m.setAttachmentMarshaller(am);
    marshal(m,object,contentHandler);
    m.setAttachmentMarshaller(null);
    context.marshallerPool.recycle(m);
}
 
Example 36
Project: openjdk-jdk10   File: MarshallerBridge.java   Source Code and License 5 votes vote down vote up
public void marshal(Marshaller m, Object object, XMLStreamWriter output) throws JAXBException {
    m.setProperty(Marshaller.JAXB_FRAGMENT,true);
    try {
        m.marshal(object,output);
    } finally {
        m.setProperty(Marshaller.JAXB_FRAGMENT,false);
    }
}
 
Example 37
Project: Hydrograph   File: ExternalOperationExpressionUtil.java   Source Code and License 5 votes vote down vote up
public void marshal(Class<?> clazz, File file,Object object) throws JAXBException{
	JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
	Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
	jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
	jaxbMarshaller.marshal(object, file);
	
}
 
Example 38
Project: MFM   File: PersistUtils.java   Source Code and License 5 votes vote down vote up
public static void saveJAXB(Object obj, String path, Class _class) {
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(_class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(obj, new File(path));
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}
 
Example 39
Project: airsonic   File: JAXBWriter.java   Source Code and License 5 votes vote down vote up
private Marshaller createXmlMarshaller() {
    Marshaller marshaller = null;
    try {
        marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, StringUtil.ENCODING_UTF8);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        return marshaller;
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }
}
 
Example 40
Project: airsonic   File: JAXBWriter.java   Source Code and License 5 votes vote down vote up
private Marshaller createJsonMarshaller() {
    try {
        Marshaller marshaller;
        marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, StringUtil.ENCODING_UTF8);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
        return marshaller;
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }
}