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

The following are Jave code examples for showing how to use setProperty() 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: Java-9-Cookbook   File: HelloWorldXml.java   Source Code and License Vote up 6 votes
public static void main(String[] args) throws JAXBException{
  //create instance of JAXBContext with the class we want to serialize into XML
  JAXBContext jaxb = JAXBContext.newInstance(Messages.class);

  //create a marshaller which will do the task of generating xml
  Marshaller marshaller = jaxb.createMarshaller();

  //setting the property of marshaller to not add the <? xml> tag
  marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

  StringWriter writer = new StringWriter();

  //serialze the Messages instance and send the string to the writer
  marshaller.marshal(new Messages(), writer);

  //get the XML from the writer
  System.out.println(writer.toString());
}
 
Example 3
Project: DIA-Umpire-Maven   File: TraMLParser.java   Source Code and License Vote up 6 votes
public String getTransitionListXML(Logger logger) 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);

        StringWriter sw = new StringWriter();
        m.marshal(tramlWrap, sw);

        return sw.toString();
    }
 
Example 4
Project: DIA-Umpire-Maven   File: TraMLCreator.java   Source Code and License Vote up 6 votes
public String asString() throws JAXBException {

        java.io.StringWriter sw = new StringWriter();
        JAXBContext ctx = JAXBContext.newInstance("org.hupo.psi.ms.traml");

        Marshaller m = ctx.createMarshaller();
        m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, JTRAML_URL.TRAML_XSD_LOCATION);
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        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, sw);

        return sw.toString();
    }
 
Example 5
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 6
Project: outcomes   File: JAXB.java   Source Code and License Vote up 5 votes
private static String convertToXml(Object obj, String encoding, boolean formattedOutput)
        throws JAXBException {
    JAXBContext context = getJAXBContext(obj.getClass());
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formattedOutput);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

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

    return writer.toString();
}
 
Example 7
Project: openjdk-jdk10   File: MarshallerBridge.java   Source Code and License Vote up 5 votes
public void marshal(Marshaller m, Object object, OutputStream output, NamespaceContext nsContext) throws JAXBException {
    m.setProperty(Marshaller.JAXB_FRAGMENT,true);
    try {
        ((MarshallerImpl)m).marshal(object,output,nsContext);
    } finally {
        m.setProperty(Marshaller.JAXB_FRAGMENT,false);
    }
}
 
Example 8
Project: OpenJSharp   File: JAXBDispatchMessage.java   Source Code and License Vote up 5 votes
@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 9
Project: redirector   File: PartnersTest.java   Source Code and License Vote up 5 votes
private String serializeIt(Partners partner, Boolean format) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Partners.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, format);

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

    return result.toString();
}
 
Example 10
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 11
Project: OpenJSharp   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 12
Project: XXXX   File: JAXBContextFactory.java   Source Code and License Vote up 5 votes
private void setMarshallerProperties(Marshaller marshaller) throws PropertyException {
  Iterator<String> keys = properties.keySet().iterator();

  while (keys.hasNext()) {
    String key = keys.next();
    marshaller.setProperty(key, properties.get(key));
  }
}
 
Example 13
Project: OpenJSharp   File: MarshallerBridge.java   Source Code and License Vote up 5 votes
public void marshal(Marshaller m, Object object, ContentHandler contentHandler) throws JAXBException {
    m.setProperty(Marshaller.JAXB_FRAGMENT,true);
    try {
        m.marshal(object,contentHandler);
    } finally {
        m.setProperty(Marshaller.JAXB_FRAGMENT,false);
    }
}
 
Example 14
Project: OpenJSharp   File: MarshallerBridge.java   Source Code and License Vote up 5 votes
public void marshal(Marshaller m, Object object, ContentHandler contentHandler) throws JAXBException {
    m.setProperty(Marshaller.JAXB_FRAGMENT,true);
    try {
        m.marshal(object,contentHandler);
    } finally {
        m.setProperty(Marshaller.JAXB_FRAGMENT,false);
    }
}
 
Example 15
Project: Layer-Query   File: GeodirQuery.java   Source Code and License Vote up 5 votes
public String saveLayerQuery(QueryConfiguration queryConfiguration) {

		final String finalQuery = queryConfiguration
				.generateSQL(this.geodirLayerManager.getLayerConfiguration().getDafaultConditions());
		if (this.geodirLayerManager.getLayerConfiguration().getLayer() == null) {
			log.info(queryConfiguration.toString());
			return finalQuery;
		}
		this.geodirLayerManager.getLayerConfiguration().getLayer().setQuery(finalQuery);
		this.geodirLayerManager.saveConfiguration();
		File parent_file = new File(
				this.geodirLayerManager.getLayerConfiguration().getLayer().getPath() + "/" + this.queryDirectory + "/");
		if (!parent_file.exists()) {
			parent_file.mkdirs();
		}
		File file = new File(parent_file, "/" + this.queryFileConf + ".xml");
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(QueryConfiguration.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			jaxbMarshaller.marshal(queryConfiguration, file);
			log.info("done..");
		} catch (JAXBException e) {
			log.error("fail creating file..", e);
		}
		return finalQuery;
	}
 
Example 16
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 17
Project: airsonic   File: JAXBWriter.java   Source Code and License Vote up 5 votes
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);
    }
}
 
Example 18
Project: orbis-lps2ima-dev   File: WpsService.java   Source Code and License Vote up 4 votes
@Override
public List<Operation> getAllOperation() {
    cachedOpList = new ArrayList<>();
    try {
        Unmarshaller unmarshaller = JaxbContainer.JAXBCONTEXT.createUnmarshaller();
        Marshaller marshaller = JaxbContainer.JAXBCONTEXT.createMarshaller();
        ObjectFactory factory = new ObjectFactory();
        //Creates the getCapabilities
        GetCapabilitiesType getCapabilitiesType = new GetCapabilitiesType();
        GetCapabilitiesType.AcceptLanguages acceptLanguages = new GetCapabilitiesType.AcceptLanguages();
        acceptLanguages.getLanguage().add("*");
        getCapabilitiesType.setAcceptLanguages(acceptLanguages);
        AcceptVersionsType acceptVersionsType = new AcceptVersionsType();
        acceptVersionsType.getVersion().add("2.0.0");
        getCapabilitiesType.setAcceptVersions(acceptVersionsType);
        SectionsType sectionsType = new SectionsType();
        sectionsType.getSection().add("All");
        getCapabilitiesType.setSections(sectionsType);
        //Marshall the DescribeProcess object into an OutputStream
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        marshaller.marshal(factory.createGetCapabilities(getCapabilitiesType), out);
        //Write the OutputStream content into an Input stream before sending it to the wpsService
        InputStream in = new DataInputStream(new ByteArrayInputStream(out.toByteArray()));
        ByteArrayOutputStream xml = (ByteArrayOutputStream) wpsServer.callOperation(in);
        //Get back the result of the DescribeProcess request as a BufferReader
        ByteArrayInputStream resultXml = new ByteArrayInputStream(xml.toByteArray());
        //Unmarshall the result and check that the object is the same as the resource unmashalled xml.
        Object resultObject = unmarshaller.unmarshal(resultXml);
        WPSCapabilitiesType wpsCapabilitiesType = (WPSCapabilitiesType) ((JAXBElement) resultObject).getValue();

        List<KeywordsType> keywordsType = null;
        ArrayList<String> listWordEnglish = new ArrayList<>();

        for(ProcessSummaryType process : wpsCapabilitiesType.getContents().getProcessSummary()){
            Operation op = new Operation(process.getTitle().get(0).getValue(), process.getIdentifier().getValue());
            if(process.getAbstract()!=null && !process.getAbstract().isEmpty()) {
                op.setAbstr(process.getAbstract().get(0).getValue());
                keywordsType = process.getKeywords();
                for(KeywordsType keyword : keywordsType){
                    for (LanguageStringType language : keyword.getKeyword()) {
                        if(language.getLang().equals("en")) {
                            op.getKeyWord().add(language.getValue());
                        }
                    }
                }
            }
            cachedOpList.add(op);
        }
    }
    catch (Exception e){
        LOGGER.error("Unable to get the list of the operations.\n"+e.getMessage());
    }
    return cachedOpList;
}
 
Example 19
Project: clearwsd   File: SemevalFactory.java   Source Code and License Vote up 4 votes
public static void writeCorpus(SemevalCorpus corpus, OutputStream outputStream) throws JAXBException {
    JAXBContext jaxb = JAXBContext.newInstance(SemevalCorpus.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(corpus, outputStream);
}
 
Example 20
Project: jaffa-framework   File: PrintXmlUtility.java   Source Code and License Vote up 3 votes
/**
 * Writes an object's XML to the specified filename.
 *
 * @param object the object.
 * @param filename the file name.
 * @throws Exception
 */
public void writeXml(Object object, String filename) throws JAXBException {
    File file = new File(filename);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(object, file);
}