Java Code Examples for javax.xml.bind.Marshaller.marshal()

The following are Jave code examples for showing how to use marshal() of the javax.xml.bind.Marshaller class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: springboot-training   File: XMLUtil.java   Source Code and License Vote up 7 votes
/**
 * 对象转为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: dss-demonstrations   File: XSLTServiceTest.java   Source Code and License Vote up 6 votes
@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 3
Project: hashsdn-controller   File: Config.java   Source Code and License Vote up 6 votes
public void toXml(final File to) {
    try {

        // TODO Moxy has to be used instead of default jaxb impl due to a bug
        // default implementation has a bug that prevents from serializing xml in a string
        JAXBContext jaxbContext = org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(new Class[]{Config.class}, null);

        Marshaller marshaller = jaxbContext.createMarshaller();

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

        marshaller.marshal(this, to);
    } catch (final JAXBException e) {
        throw new PersistException("Unable to persist configuration", e);
    }
}
 
Example 4
Project: Luna-Exam-Builder   File: Data.java   Source Code and License Vote up 6 votes
public static void saveExamToFile(File file,Exam exam){
	try {
		//prepare the marshaller
		JAXBContext context = JAXBContext.newInstance(Exam.class);
		Marshaller m = context.createMarshaller();
		//Save the exam to a file and print it pretty on the console
		m.marshal(exam,file);
		//prettify here to save space in the file
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		System.out.println(exam);
		m.marshal(exam,System.out);
		MainApp.currentFilePath = file.getAbsolutePath();

	}catch (Exception e){
		e.printStackTrace();
	}
}
 
Example 5
Project: OpenJSharp   File: JAXBMessage.java   Source Code and License Vote up 6 votes
@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 6
Project: keycloak_training   File: BindTest.java   Source Code and License Vote up 6 votes
@Test @Ignore
public void testMarschallAcessToken() throws Exception {
  
    JAXBContext jc = JAXBContext.newInstance(AccessToken.class);
    
    // Create the Marshaller Object using the JaxB Context
    Marshaller marshaller = jc.createMarshaller();
    
    marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
    marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT,false);
    AccessToken accessToken = new AccessToken();
    accessToken.setAccessToken("eyJhbGciOiJSU");
    accessToken.setExpiresIn(600);
    accessToken.setExpiresIn(60);
    accessToken.setRefreshToken("_dqAGxefbg0u58JAkz4nBkNE");
    accessToken.setTokenType("token_type");
    
    // Marshal the employee object to JSON and print the output to console
    marshaller.marshal(accessToken, System.out);
    
}
 
Example 7
Project: keycloak_training   File: BindTest.java   Source Code and License Vote up 6 votes
@Test
public void testMarschallingMessage() throws Exception {
  
    JAXBContext jc = JAXBContext.newInstance(Message.class);
    
    // Create the Marshaller Object using the JaxB Context
    Marshaller marshaller = jc.createMarshaller();
    
    marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
    marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT,false);
    Message message = new Message();
    message.setMessage("success");
    // Marshal the employee object to JSON and print the output to console
    marshaller.marshal(message, System.out);
    
}
 
Example 8
Project: OpenJSharp   File: JAXBMessage.java   Source Code and License Vote up 6 votes
/**
 * Obtains the tag name of the root element.
 */
private void sniff() {
    RootElementSniffer sniffer = new RootElementSniffer(false);
    try {
            if (rawContext != null) {
                    Marshaller m = rawContext.createMarshaller();
                    m.setProperty("jaxb.fragment", Boolean.TRUE);
                    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.
        nsUri = sniffer.getNsUri();
        localName = sniffer.getLocalName();
    }
}
 
Example 9
Project: redirector   File: DistributionTest.java   Source Code and License Vote up 5 votes
private String serializeIt(Distribution dist, Boolean format) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Distribution.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, format);

    StringWriter result = new StringWriter();
    marshaller.marshal(dist, result);

    return result.toString();
}
 
Example 10
Project: openjdk-jdk10   File: MarshallerBridge.java   Source Code and License Vote up 5 votes
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 11
Project: OpenJSharp   File: MarshallerBridge.java   Source Code and License Vote up 5 votes
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 12
Project: OpenJSharp   File: MarshallerBridge.java   Source Code and License Vote up 5 votes
public void marshal(Marshaller m, Object object, Result result) throws JAXBException {
    m.setProperty(Marshaller.JAXB_FRAGMENT,true);
    try {
        m.marshal(object,result);
    } finally {
        m.setProperty(Marshaller.JAXB_FRAGMENT,false);
    }
}
 
Example 13
Project: school-game   File: DialogDataHelper.java   Source Code and License Vote up 5 votes
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 14
Project: hadoop   File: TestRMWebServicesDelegationTokenAuthentication.java   Source Code and License Vote up 5 votes
static String getMarshalledAppInfo(ApplicationSubmissionContextInfo appInfo)
    throws Exception {

  StringWriter writer = new StringWriter();
  JAXBContext context =
      JAXBContext.newInstance(ApplicationSubmissionContextInfo.class);
  Marshaller m = context.createMarshaller();
  m.marshal(appInfo, writer);
  return writer.toString();
}
 
Example 15
Project: OpenJSharp   File: MarshallerBridge.java   Source Code and License Vote up 5 votes
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 16
Project: openjdk-jdk10   File: MarshallerBridge.java   Source Code and License Vote up 5 votes
public void marshal(Marshaller m, Object object, Node output) throws JAXBException {
    m.setProperty(Marshaller.JAXB_FRAGMENT,true);
    try {
        m.marshal(object,output);
    } finally {
        m.setProperty(Marshaller.JAXB_FRAGMENT,false);
    }
}
 
Example 17
Project: dss-demonstrations   File: FOPServiceTest.java   Source Code and License Vote up 5 votes
@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 18
Project: openjdk-jdk10   File: ExceptionBean.java   Source Code and License Vote up 5 votes
/**
 * 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: nifi-registry   File: FileAccessPolicyProvider.java   Source Code and License Vote up 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 20
Project: personium-core   File: DavResourceUtils.java   Source Code and License Vote up 4 votes
/**
 * BoxレベルACLを設定する.
 * <p>
 * 使用例:
 * <pre>
 * Acl acl = new Acl();
 * acl.getAce().add(DavResourceUtils.createAce(false, roleRead, &quot;read&quot;));
 * acl.getAce().add(DavResourceUtils.createAce(false, roleWrite, &quot;write&quot;));
 * acl.setXmlbase(String.format(&quot;%s/%s/__role/%s/&quot;,
 *         UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME));
 * DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, COL_NAME, acl, HttpStatus.SC_OK);
 * </pre>
 * </p>
 * @param token トークン
 * @param cell セル名
 * @param box ボックス名
 * @param col コレクション名
 * @param acl 設定するACLオブジェクト
 * @param code 期待するステータスコード
 * @return レスポンス
 * @throws JAXBException ACLの解析に失敗したとき
 */
public static TResponse setAcl(String token, String cell, String box, String col, Acl acl, int code)
        throws JAXBException {
    StringWriter writer = new StringWriter();
    JAXBContext context = JAXBContext.newInstance(Acl.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(acl, writer);
    return Http.request("box/acl-setting-none-body.txt")
            .with("cell", cell)
            .with("box", box)
            .with("colname", col)
            .with("token", token)
            .with("body", writer.toString())
            .returns()
            .debug()
            .statusCode(code);
}