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

The following examples show how to use javax.xml.bind.Marshaller#setProperty() . 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: OpenLabelerController.java    From OpenLabeler with Apache License 2.0 6 votes vote down vote up
private void toClipboard(ObjectModel model) {
    Clipboard clipboard = Clipboard.getSystemClipboard();
    Map<DataFormat, Object> content = new HashMap();
    try {
        Marshaller marshaller = jaxbContext.createMarshaller();
        StringWriter writer = new StringWriter();
        // output pretty printed
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        marshaller.marshal(model, writer);
        content.put(DATA_FORMAT_JAXB, writer.toString());
        content.put(DataFormat.PLAIN_TEXT, writer.toString());
        clipboard.setContent(content);
    }
    catch (Exception ex) {
        LOG.log(Level.WARNING, "Unable to put content to clipboard", ex);
    }
}
 
Example 2
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 3
Source File: DataConverter.java    From mcg-helper with Apache License 2.0 6 votes vote down vote up
public static String mcgGlobalToXml(McgGlobal mcgGlobal) {
	String result = null;
  
  try {
      ByteArrayOutputStream os = new ByteArrayOutputStream();
      JAXBContext context = JAXBContext.newInstance(McgGlobal.class);
      Marshaller m = context.createMarshaller();
      m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);   
//      m.setProperty(Marshaller.JAXB_ENCODING, "GBK"); //防止文件中文乱码  
      m.marshal(mcgGlobal, os);
      result = new String(os.toByteArray(), Constants.CHARSET);
      os.close();
  } catch (Exception e) {
      logger.error("mcgGlobal转换xml出错,mcgGlobal对象数据:{},异常信息:{}", JSON.toJSONString(mcgGlobal), e.getMessage());
  }
  
  return result;    	
}
 
Example 4
Source File: PlayerAppearanceExporter.java    From aion-germany with GNU General Public License v3.0 6 votes vote down vote up
public static void writeXml()
{
	if (newAdded > 0)
	{
		try 
		{
	        JAXBContext jaxbContext = JAXBContext.newInstance( Players.class );
	        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
	      
	        jaxbMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
	        new File("./data/appearances/").mkdirs(); 
	        jaxbMarshaller.marshal( players, new File( fileName ) );	        
		} 
		catch (JAXBException e) 
		{
			PacketSamurai.getUserInterface().log("Xml:"+ e.getMessage());
		}
		PacketSamurai.getUserInterface().log("Export [PlayerAppearance] - Written successfully "+newAdded+" new PlayerAppearances - You have now a total of ["+playerByName.size()+"] PlayerAppearances!");
		newAdded = 0;
	}
	else PacketSamurai.getUserInterface().log("Export [PlayerAppearance] - Nothing to Export..");
}
 
Example 5
Source File: HrefListingMarshaller.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(TopologiesResource.HrefListing instance,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream) throws IOException, WebApplicationException {
    try {
        Map<String, Object> properties = new HashMap<>(1);
        properties.put( JAXBContextProperties.MEDIA_TYPE, mediaType.toString());
        JAXBContext context = JAXBContext.newInstance(new Class[]{TopologiesResource.HrefListing.class}, properties);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(instance, entityStream);
    } catch (JAXBException e) {
        throw new IOException(e);
    }
}
 
Example 6
Source File: PersistenceXmlTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception
 */
public void testPersistenceVersion2() throws Exception {
    final JAXBContext ctx = JAXBContextFactory.newInstance(Persistence.class);
    final Unmarshaller unmarshaller = ctx.createUnmarshaller();

    final URL resource = this.getClass().getClassLoader().getResource("persistence_2.0-example.xml");
    final InputStream in = resource.openStream();
    final java.lang.String expected = readContent(in);

    final Persistence element = (Persistence) unmarshaller.unmarshal(new ByteArrayInputStream(expected.getBytes()));
    unmarshaller.setEventHandler(new TestValidationEventHandler());
    System.out.println("unmarshalled");

    final Marshaller marshaller = ctx.createMarshaller();
    marshaller.setProperty("jaxb.formatted.output", true);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    marshaller.marshal(element, baos);

    final String actual = new String(baos.toByteArray());

    final Diff myDiff = new Diff(expected, actual);
    myDiff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
    assertTrue("Files are similar " + myDiff, myDiff.similar());
}
 
Example 7
Source File: JaxbMapper.java    From onetwo with Apache License 2.0 6 votes vote down vote up
/**
	 * 创建Marshaller并设定encoding(可为null).
	 * 线程不安全,需要每次创建或pooling。
	 */
	public Marshaller createMarshaller(String encoding) {
		try {
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			
//			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
			
			if (StringUtils.isNotBlank(encoding)) {
				marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
			}

			return marshaller;
		} catch (JAXBException e) {
			LangUtils.throwBaseException(e);
		}
		return null;
	}
 
Example 8
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 9
Source File: MarshallerBridge.java    From jdk8u60 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 10
Source File: MarshallerBridge.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
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 11
Source File: TestApiWidgetTypeInterface.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected String getMarshalledObject(Object object) throws Throwable {
    JAXBContext context = JAXBContext.newInstance(object.getClass());
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    StringWriter writer = new StringWriter();
    marshaller.marshal(object, writer);
    return writer.toString();
}
 
Example 12
Source File: PaymentTool.java    From maintain with MIT License 5 votes vote down vote up
public static void generateCbecMessageCiq(Object object, String dir, String backDir) {
		if (null == object) {
			return;
		}
		JAXBContext context = null;
		Marshaller marshaller = null;
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		SimpleDateFormat sdfToday = new SimpleDateFormat("yyyyMMdd");
		String fileName = "FILE_PAYMENT_" + sdf.format(calendar.getTime());
		File cbecMessage = new File(dir + fileName + ".xml");
		File backCbecMessage = new File(backDir + sdfToday.format(calendar.getTime()) + "/" + fileName + ".xml");
		File backDirFile = new File(backDir + sdfToday.format(calendar.getTime()));
		try {
			context = JAXBContext.newInstance(object.getClass());
			marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
			
			if (!backDirFile.exists()) {
				backDirFile.mkdir();
			}
			
			marshaller.marshal(object, backCbecMessage);
			marshaller.marshal(object, cbecMessage);
		} catch (Exception e) {
			e.printStackTrace();
			logger.equals(e);
		}
	}
 
Example 13
Source File: PrintJUDDI.java    From juddi with Apache License 2.0 5 votes vote down vote up
private Marshaller getUDDIMarshaller() throws JAXBException {
	if (jaxbContext==null) {
		jaxbContext=JAXBContext.newInstance("org.apache.juddi.api_v3");
	}
	Marshaller marshaller = jaxbContext.createMarshaller();
	marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
	marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
	marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
	
	return marshaller;
}
 
Example 14
Source File: SunCmpConversionTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private String toString(final EntityMappings entityMappings) throws JAXBException {
    final JAXBContext entityMappingsContext = JAXBContextFactory.newInstance(EntityMappings.class);

    final Marshaller marshaller = entityMappingsContext.createMarshaller();
    marshaller.setProperty("jaxb.formatted.output", true);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    marshaller.marshal(entityMappings, baos);

    final String actual = new String(baos.toByteArray());
    return actual.trim();
}
 
Example 15
Source File: JaxbUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
private static <T> Marshaller createXmlMarshaller(T object, boolean doFormatting, Class<?>... nestedClasses) throws JAXBException {
	Class<?>[] targetClasses = merge(object.getClass(), nestedClasses);
	JAXBContext jc = createJAXBContext(targetClasses);
	Marshaller marshaller = jc.createMarshaller();
	marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, doFormatting);
	marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
	logger.debug("Using Marshaller of type: " + marshaller.getClass().getName());
	
	XmlFormat format = XmlFormat.resolveFromClazz(object.getClass());
	if(format != null && !format.equals(XmlFormat.UNKNOWN)) {
		marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, format.xsiSchemaLocation);
	}
	logger.debug(marshaller.getClass().getCanonicalName());
	return marshaller;
}
 
Example 16
Source File: JAXBPayload.java    From jlibs with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(OutputStream out) throws IOException{
    try{
        Marshaller m = context.createMarshaller();
        if(format)
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal(bean, out);
    }catch(JAXBException ex){
        throw new IOException(ex);
    }
}
 
Example 17
Source File: JAXBMessage.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void writePayloadTo(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.TRUE);
            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
        //am.cleanup();
    } catch (JAXBException e) {
        // bug 6449684, spec 4.3.4
        throw new WebServiceException(e);
    }
}
 
Example 18
Source File: MCRJAXBContent.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
private Marshaller getMarshaller() throws JAXBException {
    Marshaller marshaller = ctx.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, getSafeEncoding());
    return marshaller;
}
 
Example 19
Source File: XmlConfigUtils.java    From openjdk-8-source with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Writes the given bean to the given output stream.
 * @param bean the bean to write.
 * @param os the output stream to write to.
 * @param fragment whether the {@code <?xml ... ?>} header should be
 *        included. The header is not included if the bean is just an
 *        XML fragment encapsulated in a higher level XML element.
 * @throws JAXBException An XML Binding exception occurred.
 **/
private static void writeXml(Object bean, OutputStream os, boolean fragment)
    throws JAXBException {
    final Marshaller m = createMarshaller();
    if (fragment) m.setProperty(m.JAXB_FRAGMENT,Boolean.TRUE);
    m.marshal(bean,os);
}
 
Example 20
Source File: JSONExporter.java    From txtUML with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Serializes an Object to JSON and writes it using the writer provided
 * 
 * @param object
 *            Object to write as JSON, which must have a no-arg constructor.
 * @param jsonfile
 *            BufferedWriter to write JSON Object into
 * @throws JAXBException
 */
public static void writeObjectAsJSON(Object object, BufferedWriter jsonfile) throws JAXBException {
	JAXBContext jc = JAXBContextFactory.createContext(new Class[] { object.getClass(), ObjectFactory.class }, null);
	Marshaller marshaller = jc.createMarshaller();
	marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
	marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
	marshaller.marshal(object, jsonfile);
}