javax.xml.bind.Marshaller Java Examples

The following examples show how to use javax.xml.bind.Marshaller. 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: JAXBMessage.java    From openjdk-8-source with GNU General Public License v2.0 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 #2
Source File: OutTransformWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testNamespaceConversion() throws Exception {
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();

    JAXBContext context = JAXBContext.newInstance(TestBean.class);
    Marshaller m = context.createMarshaller();
    Map<String, String> outMap = new HashMap<>();
    outMap.put("{http://testbeans.com}testBean", "{http://testbeans.com/v2}testBean");
    outMap.put("{http://testbeans.com}bean", "{http://testbeans.com/v3}bean");
    OutTransformWriter transformWriter = new OutTransformWriter(writer,
                                                                outMap,
                                                                Collections.<String, String>emptyMap(),
                                                                Collections.<String>emptyList(),
                                                                false,
                                                                "");
    m.marshal(new TestBean(), transformWriter);

    Element el = writer.getDocument().getDocumentElement();
    assertEquals("http://testbeans.com/v2", el.getNamespaceURI());
    assertFalse(StringUtils.isEmpty(el.getPrefix()));

    Element el2 = DOMUtils.getFirstElement(el);
    assertEquals("http://testbeans.com/v3", el2.getNamespaceURI());
    assertFalse(StringUtils.isEmpty(el2.getPrefix()));

}
 
Example #3
Source File: JAXBMessage.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #4
Source File: MarshallerPool.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an configures a new JAXB marshaller.
 * This method is invoked only when no existing marshaller is available in the pool.
 * Subclasses can override this method if they need to change the marshaller configuration.
 *
 * @return a new marshaller configured for formatting OGC/ISO XML.
 * @throws JAXBException if an error occurred while creating and configuring the marshaller.
 *
 * @see #context
 * @see #acquireMarshaller()
 */
protected Marshaller createMarshaller() throws JAXBException {
    final Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    /*
     * Note: we do not set the Marshaller.JAXB_ENCODING property because specification
     * said that the default value is "UTF-8", which is what we want.
     */
    String key;
    if ((key = implementation.indentKey) != null) {
        marshaller.setProperty(key, CharSequences.spaces(Constants.DEFAULT_INDENTATION));
    }
    synchronized (replacements) {
        for (final AdapterReplacement adapter : replacements) {
            adapter.register(marshaller);
        }
    }
    return marshaller;
}
 
Example #5
Source File: JaxbUtils.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Marshal the provided object using the OutputStream specified
 *
 * @param objectToMarshal
 * @param outputStream
 * @throws JAXBException
 */
public static void marshal(Object objectToMarshal, OutputStream outputStream) throws JAXBException {
    if (objectToMarshal != null) {
        long startTime = System.currentTimeMillis();
        
        JAXBContext context = JAXBContext.newInstance(objectToMarshal.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
        marshaller.marshal(objectToMarshal, outputStream);

        System.out.println("marshaled " + objectToMarshal.getClass() + " in: "
                + (System.currentTimeMillis() - startTime));
    } else {
        throw new IllegalArgumentException("Cannot marshal null object");
    }
}
 
Example #6
Source File: JAXBMessage.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #7
Source File: BehaviorCatalog.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public synchronized void init() {
   try{
      URL url = Resources.getResource("com/iris/common/subsystem/care/behavior/behavior_catalog.xml");
      JAXBContext context = JAXBContext.newInstance(BehaviorCatalog.class);
      Marshaller m = context.createMarshaller();
      BehaviorCatalog catalog = (BehaviorCatalog) context.createUnmarshaller().unmarshal(url);
      behavior = catalog.getBehavior();
      behaviorMap = new HashMap<String, BehaviorCatalog.BehaviorCatalogTemplate>(behavior.size());
      for (BehaviorCatalogTemplate catTemplate : behavior){
         behaviorMap.put(catTemplate.id, catTemplate);
      }

   }catch (Exception e){
      throw new RuntimeException(e);
   }
}
 
Example #8
Source File: XMLConverUtil.java    From springboot-security-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Object to XML
 * @param object object
 * @return xml
 */
public static String convertToXML(Object object){
	try {
		Map<Class<?>, Marshaller> mMap = mMapLocal.get();
		if(!mMap.containsKey(object.getClass())){
			JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			//设置CDATA输出字符
			marshaller.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() {
				public void escape(char[] ac, int i, int j, boolean flag, Writer writer) throws IOException {
					writer.write(ac, i, j);
				}
			});
			mMap.put(object.getClass(), marshaller);
		}
		StringWriter stringWriter = new StringWriter();
		mMap.get(object.getClass()).marshal(object,stringWriter);
		return stringWriter.getBuffer().toString();
	} catch (JAXBException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #9
Source File: StandardSnippetSerializer.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public static byte[] serialize(final StandardSnippet snippet) {
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final BufferedOutputStream bos = new BufferedOutputStream(baos);

        JAXBContext context = JAXBContext.newInstance(StandardSnippet.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(snippet, bos);

        bos.flush();
        return baos.toByteArray();
    } catch (final IOException | JAXBException e) {
        throw new FlowSerializationException(e);
    }
}
 
Example #10
Source File: ApiBaseTestCase.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected String marshall(Object result, MediaType mediaType) throws Throwable {
	if (null != mediaType && mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
		JSONProvider jsonProvider = (JSONProvider) super.getApplicationContext().getBean("jsonProvider");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		jsonProvider.writeTo(result, result.getClass().getGenericSuperclass(), 
				result.getClass().getAnnotations(), mediaType, null, baos);
		return new String(baos.toByteArray(), "UTF-8");
	} else {
		JAXBContext context = JAXBContext.newInstance(result.getClass());
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.setProperty("com.sun.xml.bind.marshaller.CharacterEscapeHandler", new CDataCharacterEscapeHandler());
		StringWriter writer = new StringWriter();
		marshaller.marshal(result, writer);
		return writer.toString();
	}
}
 
Example #11
Source File: XmlUtil.java    From wechat-mp-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * object -> xml
 *
 * @param object
 * @param childClass
 */
public static String marshal(Object object) {
    if (object == null) {
        return null;
    }

    try {
        JAXBContext jaxbCtx = JAXBContext.newInstance(object.getClass());

        Marshaller marshaller = jaxbCtx.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        StringWriter sw = new StringWriter();
        marshaller.marshal(object, sw);

        return sw.toString();
    } catch (Exception e) {
    }

    return null;
}
 
Example #12
Source File: XACMLPolicyWriter.java    From XACML with MIT License 5 votes vote down vote up
/**
 * Helper static class that does the work to write a policy set to an output stream.
 * 
 * @param os
 * @param policy
 */
public static void writePolicyFile(OutputStream os, PolicyType policy) {
	JAXBElement<PolicyType> policySetElement = new ObjectFactory().createPolicy(policy);		
	try {
		JAXBContext context = JAXBContext.newInstance(PolicyType.class);
		Marshaller m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		m.marshal(policySetElement, os);
	} catch (JAXBException e) {
		logger.error(MSG_WRITE, e);
	}
}
 
Example #13
Source File: MCRJAXBContent.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Document asXML() throws JDOMException, IOException, SAXParseException {
    JDOMResult result = new JDOMResult();
    try {
        Marshaller marshaller = getMarshaller();
        marshaller.marshal(jaxbObject, result);
    } catch (JAXBException e) {
        throw new IOException(e);
    }
    return result.getDocument();
}
 
Example #14
Source File: MarshallerBridge.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
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 #15
Source File: Bridge.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 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 #16
Source File: MarshallerBridge.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
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
Source File: MarshallerBridge.java    From TencentKona-8 with GNU General Public License v2.0 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 #18
Source File: ReadXMLFileUtils.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
public static ByteArrayOutputStream convertDossierTemplateToXMLStream(DossierTemplate dossierTemplate)
		throws JAXBException {
	ByteArrayOutputStream dossierTemplateXMLStream = new ByteArrayOutputStream();
	JAXBContext jaxbContext = JAXBContext.newInstance(DossierTemplate.class);
	Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
	//for pretty-print XML in JAXB
	jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
	//Store XML to File

	jaxbMarshaller.marshal(dossierTemplate, dossierTemplateXMLStream);
	//out log in server
	//jaxbMarshaller.marshal(dictCollection, System.out);
	return dossierTemplateXMLStream;
}
 
Example #19
Source File: XmlProcessBase.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
/**
 * baseParseAndWriteToXml
 *
 * @param user
 * @param inputPath
 * @param name
 * @Created 2016/9/15
 */
public void baseParseAndWriteToXml(Object user, String inputPath, String name) throws IOException {
    OutputStream out = null;
    try {
        Marshaller marshaller = this.jaxContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        if (null != name) {
            marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders",
                    String.format("<!DOCTYPE " + Versions.ROOT_PREFIX + ":%1$s SYSTEM \"%1$s.dtd\">", name));
        }

        Path path = Paths.get(inputPath);

        out = Files.newOutputStream(path, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);

        marshaller.marshal(user, out);

    } catch (JAXBException | IOException e) {
        LOGGER.error("ZookeeperProcessListen parseToXml  error:Exception info:", e);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}
 
Example #20
Source File: SIP2DESATransporter.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Initialize JAXB transformers
 *
 * @throws JAXBException
 */
private void initJAXB() throws JAXBException {
    if (marshaller != null) {
        return ;
    }
    JAXBContext jaxbContext = getPspipJaxb();
    marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    unmarshaller = jaxbContext.createUnmarshaller();
}
 
Example #21
Source File: JsonProviderPrototypeServiceFactory.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
JsonProviderPrototypeServiceFactory(
    Dictionary<String, ?> properties,
    Optional<TypeConverter> typeConverter,
    Optional<Marshaller.Listener> marshallerListener,
    Optional<Unmarshaller.Listener> unmarshallerListener,
    Optional<SchemaHandler> schemaHandler
) {
    _properties = properties;
    _typeConverter = typeConverter;
    _marshallerListener = marshallerListener;
    _unmarshallerListener = unmarshallerListener;
    _schemaHandler = schemaHandler;
}
 
Example #22
Source File: NsesssUtils.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
public static void marshal(Result target, Object object, boolean indent) {
    try {
        Marshaller m = defaultMarshaller(indent);
        m.marshal(object, target);
    } catch (JAXBException ex) {
        throw new DataBindingException(ex);
    }
}
 
Example #23
Source File: JaxbUtils.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] toByte(CtRichiestaPagamentoTelematico rpt) throws JAXBException, SAXException {
	init();
	Marshaller jaxbMarshaller = jaxbRptRtContext.createMarshaller();
	jaxbMarshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	jaxbMarshaller.marshal(new ObjectFactory().createRPT(rpt), baos);
	return baos.toByteArray();
}
 
Example #24
Source File: JAXBDispatchMessage.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void writeTo(XMLStreamWriter sw) throws XMLStreamException {
    try {
        // MtomCodec sets its own AttachmentMarshaller
        AttachmentMarshaller am = (sw instanceof MtomStreamWriter)
                ? ((MtomStreamWriter) sw).getAttachmentMarshaller()
                : new AttachmentMarshallerImpl(attachmentSet);

        // Get the encoding of the writer
        String encoding = XMLStreamWriterUtil.getEncoding(sw);

        // Get output stream and use JAXB UTF-8 writer
        OutputStream os = bridge.supportOutputStream() ? XMLStreamWriterUtil.getOutputStream(sw) : null;
        if (rawContext != null) {
            Marshaller m = rawContext.createMarshaller();
            m.setProperty("jaxb.fragment", Boolean.FALSE);
            m.setAttachmentMarshaller(am);
            if (os != null) {
                m.marshal(jaxbObject, os);
            } else {
                m.marshal(jaxbObject, sw);
            }

        } else {

            if (os != null && encoding != null && encoding.equalsIgnoreCase(SOAPBindingCodec.UTF8_ENCODING)) {
                bridge.marshal(jaxbObject, os, sw.getNamespaceContext(), am);
            } else {
                bridge.marshal(jaxbObject, sw, am);
            }
        }
        //cleanup() is not needed since JAXB doesn't keep ref to AttachmentMarshaller
    } catch (JAXBException e) {
        // bug 6449684, spec 4.3.4
        throw new WebServiceException(e);
    }
}
 
Example #25
Source File: MarshallerBridge.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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 #26
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 #27
Source File: BulkResultsFileOutputMapper.java    From datawave with Apache License 2.0 5 votes vote down vote up
public static String serializeQuery(Query q) throws JAXBException {
    StringWriter writer = new StringWriter();
    JAXBContext ctx = JAXBContext.newInstance(q.getClass());
    Marshaller m = ctx.createMarshaller();
    m.marshal(q, writer);
    // Probably need to base64 encode it so that it will not mess up the Hadoop Configuration object
    return Base64.encodeBytes(writer.toString().getBytes());
}
 
Example #28
Source File: Test.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 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 #29
Source File: JAXBUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get the JAXB Marshaller
 *
 * @param pkgName The package name for the jaxb context
 *
 * @return Marshaller
 *
 * @throws JAXBException
 */
public static Marshaller getMarshaller(String pkgName) throws JAXBException {
    if (pkgName == null)
        throw logger.nullArgumentError("pkgName");

    JAXBContext jc = getJAXBContext(pkgName);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, GeneralConstants.SAML_CHARSET_NAME);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE); // Breaks signatures
    return marshaller;
}
 
Example #30
Source File: JaxbSerialization.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
public <T> void serialize(final OutputStream os, final T object) throws SerializerException {
    if (object == null) {
        return;
    }
    try {
        JAXBContext context = getJaxbContext(object.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(object, os);
    } catch (JAXBException e) {
        throw new SerializerException(String.format("Error occurs while serializing %s", object.getClass()), e);
    }
}