Java Code Examples for com.thoughtworks.xstream.io.HierarchicalStreamWriter

The following examples show how to use com.thoughtworks.xstream.io.HierarchicalStreamWriter. These examples are extracted from open source projects. 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 Project: depan   Source File: GraphModelConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * No need to start a node, since the caller ensures we are wrapped correctly.
 */
@Override
public void marshal(Object source, HierarchicalStreamWriter writer,
    MarshallingContext context) {
  GraphModel graph = (GraphModel) source;

  // Save all nodes.
  for (GraphNode node : graph.getNodes()) {
    marshalObject(node, writer, context);
  }

  // Save all edges.
  for (GraphEdge edge : graph.getEdges()) {
    marshalObject(edge, writer, context);
  }
}
 
Example 2
Source Project: yes-cart   Source File: DateTimeConverterImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
    if (source == null) {
        writer.setValue("");
    } else if (source instanceof LocalDate) {
        writer.setValue(((LocalDate) source).atStartOfDay().format(DateTimeFormatter.ISO_DATE_TIME));
    } else if (source instanceof LocalDateTime) {
        writer.setValue(((LocalDateTime) source).format(DateTimeFormatter.ISO_DATE_TIME));
    } else if (source instanceof ZonedDateTime) {
        writer.setValue(((ZonedDateTime) source).format(DateTimeFormatter.ISO_DATE_TIME));
    } else if (source instanceof Instant) {
        writer.setValue(ZonedDateTime.ofInstant((Instant) source, DateUtils.zone()).format(DateTimeFormatter.ISO_DATE_TIME));
    } else {
        writer.setValue(source.toString());
    }
}
 
Example 3
@Override
public void marshal(Object original, HierarchicalStreamWriter writer, MarshallingContext context) {
  super.marshal(original, writer, context);
  WxPayOrderNotifyResult obj = (WxPayOrderNotifyResult) original;
  List<WxPayOrderNotifyCoupon> list = obj.getCouponList();
  if (list == null || list.size() == 0) {
    return;
  }
  for (int i = 0; i < list.size(); i++) {
    WxPayOrderNotifyCoupon coupon = list.get(i);
    writer.startNode("coupon_id_" + i);
    writer.setValue(coupon.getCouponId());
    writer.endNode();
    writer.startNode("coupon_type_" + i);
    writer.setValue(coupon.getCouponType());
    writer.endNode();
    writer.startNode("coupon_fee_" + i);
    writer.setValue(coupon.getCouponFee() + "");
    writer.endNode();
  }
}
 
Example 4
Source Project: brooklyn-server   Source File: StringKeyMapConverter.java    License: Apache License 2.0 6 votes vote down vote up
protected void marshalStringKey(HierarchicalStreamWriter writer, MarshallingContext context, Entry entry) {
    String key = (String)entry.getKey();
    String entryNodeName = getEntryNodeName();
    boolean useKeyAsNodeName = (!key.equals(entryNodeName) && isKeyValidForNodeName(key));
    if (useKeyAsNodeName) entryNodeName = key;
    ExtendedHierarchicalStreamWriterHelper.startNode(writer, entryNodeName, Map.Entry.class);
    if (!useKeyAsNodeName)
        writer.addAttribute("key", key);
    
    Object value = entry.getValue();
    if (entry.getValue()!=null && isInlineableType(value.getClass())) {
        if (!(value instanceof String))
            writer.addAttribute("type", mapper().serializedClass(entry.getValue().getClass()));
        if (entry.getValue().getClass().isEnum())
            writer.setValue(((Enum)entry.getValue()).name());
        else
            writer.setValue(""+entry.getValue());
    } else {
        writeItem(entry.getValue(), context, writer);
    }
    
    writer.endNode();
}
 
Example 5
Source Project: jeewx   Source File: MessageUtil.java    License: Apache License 2.0 6 votes vote down vote up
public HierarchicalStreamWriter createWriter(Writer out) {
    return new PrettyPrintWriter(out) {
        // 对所有xml节点的转换都增加CDATA标记
        boolean cdata = true;

        @SuppressWarnings("unchecked")
        public void startNode(String name, Class clazz) {
            super.startNode(name, clazz);
        }

        protected void writeText(QuickWriter writer, String text) {
            if (cdata) {
                    writer.write("<![CDATA[");
                    writer.write(text);
                    writer.write("]]>");
            } else {
                    writer.write(text);
            }
        }
    };
}
 
Example 6
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
	BeanDefinitionHolder holder = (BeanDefinitionHolder) source;
	BeanDefinition definition = holder.getBeanDefinition();
	writer.addAttribute("class", definition.getBeanClassName());
	writer.addAttribute("name", holder.getBeanName());
	for (PropertyValue property : definition.getPropertyValues().getPropertyValueList()) {
		writer.startNode("property");
		writer.addAttribute("name", property.getName());
		if (property.getValue().getClass().equals(TypedStringValue.class)) {
			context.convertAnother(property.getValue());
		} else {
			writeItem(property.getValue(), context, writer);
		}
		writer.endNode();
	}
}
 
Example 7
Source Project: lams   Source File: PropertiesConverter.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
    final Properties properties = (Properties) source;
    Map map = sort ? (Map)new TreeMap(properties) : (Map)properties;
    for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
        Map.Entry entry = (Map.Entry) iterator.next();
        writer.startNode("property");
        writer.addAttribute("name", entry.getKey().toString());
        writer.addAttribute("value", entry.getValue().toString());
        writer.endNode();
    }
    if (defaultsField != null) {
        Properties defaults = (Properties)Fields.read(defaultsField, properties);
        if (defaults != null) {
            writer.startNode("defaults");
            marshal(defaults, writer, context);
            writer.endNode();
        }
    }
}
 
Example 8
Source Project: weblaf   Source File: LocaleConverter.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void marshal ( final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context )
{
    final Locale locale = ( Locale ) source;

    // Adding language
    writer.addAttribute ( "language", locale.getLanguage () );

    // Adding country
    final String country = locale.getCountry ();
    if ( TextUtils.notEmpty ( country ) )
    {
        writer.addAttribute ( "country", country );
    }

    // Adding country
    final String variant = locale.getVariant ();
    if ( TextUtils.notEmpty ( variant ) )
    {
        writer.addAttribute ( "variant", variant );
    }
}
 
Example 9
Source Project: olat   Source File: GlossaryItemManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * writes glossary to xml-file prepend doc-book dtd: <!DOCTYPE glossary PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
 * "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
 * 
 * @param glossaryFile
 * @param glossaryItemArr
 */
private void saveToFile(VFSLeaf glossaryFile, ArrayList<GlossaryItem> glossaryItemArr) {
    // cdata-tags should be used instead of strings, overwrite writer.
    XStream xstream = new XStream(new XppDriver() {
        @Override
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                @Override
                protected void writeText(QuickWriter writer, String text) {
                    if (text.contains("<") || text.contains(">") || text.contains("&")) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    } else {
                        writer.write(text);
                    }
                }
            };
        }
    });

    xstream.alias(XML_GLOSSARY_ITEM_NAME, GlossaryItem.class);
    glossaryItemArr = removeEmptyGlossaryItems(glossaryItemArr);
    XStreamHelper.writeObject(xstream, glossaryFile, glossaryItemArr);
}
 
Example 10
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
	ManagedMap<?, ?> map = (ManagedMap<?, ?>) source;
	for (Map.Entry<?, ?> entry : map.entrySet()) {
		writer.startNode("entry");
		writer.startNode("key");
		if (entry.getKey().getClass().equals(TypedStringValue.class)) {
			writer.startNode("value");
			writer.setValue(((TypedStringValue) entry.getKey()).getValue());
			writer.endNode();
		} else {
			writeItem(entry.getKey(), context, writer);
		}
		writer.endNode();
		if (entry.getValue().getClass().equals(TypedStringValue.class)) {
			writer.startNode("value");
			writer.setValue(((TypedStringValue) entry.getValue()).getValue());
			writer.endNode();
		} else {
			writeItem(entry.getValue(), context, writer);
		}
		writer.endNode();
	}
}
 
Example 11
Source Project: bamboobsc   Source File: OlapUtils.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
      	
          AbstractMap map = (AbstractMap) value;
          for (Object obj : map.entrySet()) {
              Map.Entry entry = (Map.Entry) obj;
              writer.startNode(entry.getKey().toString());
              Object val = entry.getValue();
              if ( null != val ) {
                  writer.setValue(val.toString());
              }
              writer.endNode();
          }

      }
 
Example 12
public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext context) {
  Attribute attribute = (Attribute)object;
  writer.startNode("label");
  writer.setValue(attribute.getLabel());
  writer.endNode();
  writer.startNode("table");
  writer.setValue(attribute.getTable().getLabel());
  writer.endNode();
}
 
Example 13
Source Project: kogito-runtimes   Source File: AbstractXStreamConverter.java    License: Apache License 2.0 5 votes vote down vote up
protected void writeString(HierarchicalStreamWriter writer, String name, String value) {
    if (value != null) {
        writer.startNode(name);
        writer.setValue(value);
        writer.endNode();
    }
}
 
Example 14
public HierarchicalStreamWriter createWriter(OutputStream out) {
    try {
        // JSON spec requires UTF-8
        return createWriter(new OutputStreamWriter(out, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new StreamException(e);
    }
}
 
Example 15
Source Project: brooklyn-server   Source File: StringKeyMapConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void marshalEntry(HierarchicalStreamWriter writer, MarshallingContext context, Entry entry) {
    if (entry.getKey() instanceof String) {
        marshalStringKey(writer, context, entry);
    } else {
        super.marshalEntry(writer, context, entry);
    }
}
 
Example 16
Source Project: ET_Redux   Source File: MeasuredRatioModelXMLConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * writes the argument <code>value</code> to the XML file specified through <code>writer</code>
 * 
 * @pre     <code>value</code> is a valid <code>MeasuredRatioModel</code>,
 *          <code>writer</code> is a valid <code>HierarchicalStreamWriter</code>,
 *          and <code>context</code> is a valid <code>MarshallingContext</code>
 * @post    <code>value</code> is written to the XML file specified via <code>writer</code>
 * @param   value   <code>MeasuredRatioModel</code> that you wish to write to a file
 * @param   writer  stream to write through
 * @param   context <code>MarshallingContext</code> used to store generic data
 */
public void marshal(Object value, HierarchicalStreamWriter writer,
        MarshallingContext context) {

    ValueModel measuredRatio = (MeasuredRatioModel) value;

    writer.startNode("name");
    writer.setValue(measuredRatio.getName());
    writer.endNode();

    writer.startNode("value");
    writer.setValue(measuredRatio.getValue().toPlainString());
    writer.endNode();

    writer.startNode("uncertaintyType");
    writer.setValue(measuredRatio.getUncertaintyType());
    writer.endNode();

    writer.startNode("oneSigma");
    writer.setValue(measuredRatio.getOneSigma().toPlainString());
    writer.endNode();

    writer.startNode("fracCorr");
    writer.setValue(Boolean.toString(((MeasuredRatioModel) measuredRatio).isFracCorr()));
    writer.endNode();

    writer.startNode("oxideCorr");
    writer.setValue(Boolean.toString(((MeasuredRatioModel) measuredRatio).isOxideCorr()));
    writer.endNode();

}
 
Example 17
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
	BeanDefinition definition = (BeanDefinition) source;
	writer.addAttribute("class", definition.getBeanClassName());
	for (PropertyValue property : definition.getPropertyValues().getPropertyValueList()) {
		writer.startNode("property");
		writer.addAttribute("name", property.getName());
		if (property.getValue().getClass().equals(TypedStringValue.class)) {
			context.convertAnother(property.getValue());
		} else {
			writeItem(property.getValue(), context, writer);
		}
		writer.endNode();
	}

}
 
Example 18
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
    GregorianCalendar calendar = (GregorianCalendar) source;
    ExtendedHierarchicalStreamWriterHelper.startNode(writer, "time", long.class);
    long timeInMillis = calendar.getTime().getTime(); // calendar.getTimeInMillis() not available under JDK 1.3
    writer.setValue(String.valueOf(timeInMillis));
    writer.endNode();
    ExtendedHierarchicalStreamWriterHelper.startNode(writer, "timezone", String.class);
    writer.setValue(calendar.getTimeZone().getID());
    writer.endNode();
}
 
Example 19
Source Project: gama   Source File: GamaGraphConverter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void marshal(final Object arg0, final HierarchicalStreamWriter writer, final MarshallingContext arg2) {
	final GamaGraph graph = (GamaGraph) arg0;

//	System.out.println("ConvertAnother : GamaList " + graph.getClass());
	DEBUG.OUT("ConvertAnother : GamaList " + graph.getClass());
	arg2.convertAnother(new GamaGraphReducer(convertScope.getScope(), graph));
//	System.out.println("END --- ConvertAnother : GamaList ");
	DEBUG.OUT("END --- ConvertAnother : GamaList ");
}
 
Example 20
Source Project: onedev   Source File: MapConverter.java    License: MIT License 5 votes vote down vote up
@Override
protected void writeCompleteItem(Object item, MarshallingContext context, HierarchicalStreamWriter writer) {
	if (item instanceof VersionedXmlDoc) 
		((VersionedXmlDoc)item).marshall(writer);
	else 
		super.writeCompleteItem(item, context, writer);
}
 
Example 21
Source Project: vraptor4   Source File: XStreamXMLSerialization.java    License: Apache License 2.0 5 votes vote down vote up
protected HierarchicalStreamWriter getWriter() {
	try {
		PrintWriter writer = response.getWriter();
		return indented ? new PrettyPrintWriter(writer) : new CompactWriter(writer);
	} catch (IOException e) {
		throw new ResultException("Unable to serialize data", e);
	}
}
 
Example 22
Source Project: gama   Source File: GamaListConverter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void marshal(final Object arg0, final HierarchicalStreamWriter writer, final MarshallingContext arg2) {
	final IList list = (IList) arg0;

	// System.out.println("ConvertAnother : GamaList " + list.getClass()+ " "+list.getGamlType().getContentType());
	DEBUG.OUT("ConvertAnother : IList " + list.getClass() + " " + list.getGamlType().getContentType());
	arg2.convertAnother(new GamaListReducer(list));
	// System.out.println("END --- ConvertAnother : GamaList ");
	DEBUG.OUT("END --- ConvertAnother : GamaList ");

}
 
Example 23
Source Project: gama   Source File: GamaSpeciesConverter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void marshal(final Object arg0, final HierarchicalStreamWriter writer, final MarshallingContext context) {
	// System.out.println("ConvertAnother : ConvertGamaSpecies " + arg0.getClass());
	DEBUG.OUT("ConvertAnother : ConvertGamaSpecies " + arg0.getClass());
	final AbstractSpecies spec = (AbstractSpecies) arg0;
	final GamaPopulation<? extends IAgent> pop =
			(GamaPopulation<? extends IAgent>) spec.getPopulation(convertScope.getScope());

	writer.startNode("agentSetFromPopulation");
	context.convertAnother(pop.getAgents(convertScope.getScope()));
	writer.endNode();

	// System.out.println("===========END ConvertAnother : ConvertGamaSpecies");
	DEBUG.OUT("===========END ConvertAnother : ConvertGamaSpecies");
}
 
Example 24
Source Project: brooklyn-server   Source File: MapConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
    @SuppressWarnings({ "rawtypes" })
    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
        Map map = (Map) source;
        try {
            for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
                Map.Entry entry = (Map.Entry) iterator.next();
                marshalEntry(writer, context, entry);
            }
        } catch (ConcurrentModificationException e) {
            log.debug("Map "
                // seems there is no non-deprecated way to get the path...
                + (context instanceof ReferencingMarshallingContext ? "at "+((ReferencingMarshallingContext)context).currentPath() : "")
                + "["+source+"] modified while serializing; will fail, and retry may be attempted");
            throw e;
            // would be nice to attempt to re-serialize being slightly more defensive, as code below;
            // but the code above may have written partial data so that is dangerous, we could have corrupted output. 
            // if we could mark and restore in the output stream then we could do this below (but we don't have that in our stream),
            // or we could try this copying code in the first instance (but that's slow);
            // error is rare most of the time (e.g. attribute being updated) so we bail on this whole attempt
            // and simply try serializing the map-owner (e.g. an entity) again.
//            ImmutableList entries = ImmutableList.copyOf(map.entrySet());
//            for (Iterator iterator = entries.iterator(); iterator.hasNext();) {
//                Map.Entry entry = (Map.Entry) iterator.next();
//                marshalEntry(writer, context, entry);                
//            }
        }
    }
 
Example 25
Source Project: gatf   Source File: MapKeyValueCustomXstreamConverter.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void marshal(final Object value, final HierarchicalStreamWriter writer, final MarshallingContext context)
   {
       final AbstractMap<String, String> map = (AbstractMap<String, String>) value;
       for (final Entry<String, String> entry : map.entrySet())
       {
           writer.startNode(entry.getKey().toString());
           writer.setValue(entry.getValue().toString());
           writer.endNode();
       }
   }
 
Example 26
Source Project: lams   Source File: SystemClockConverter.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
    final Clock clock = (Clock)source;
    ExtendedHierarchicalStreamWriterHelper.startNode(writer, mapper.serializedMember(Clock.class, "zone"), null);
    context.convertAnother(clock.getZone());
    writer.endNode();
}
 
Example 27
Source Project: depan   Source File: FileDocumentReferenceConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Simply output the workspace relative name for the referenced GraphModel.
 */
@Override
public void marshal(
    Object source, HierarchicalStreamWriter writer,
    MarshallingContext context) {
  FileDocumentReference<?> docRef = (FileDocumentReference<?>) source;
  String location =
      PlatformTools.fromPath(docRef.getLocation().getFullPath());

  writer.startNode(FILE_DOC_REF_TAG);
  writer.addAttribute(DOC_PATH_ATTR, location);
  writer.endNode();
}
 
Example 28
Source Project: engage-api-client   Source File: XStreamFactory.java    License: Apache License 2.0 5 votes vote down vote up
public XStream createXStream() {
	return new XStream(
		new XppDriver() {
			@Override
			public HierarchicalStreamWriter createWriter(Writer out) {
                   return new XmlApiPrintWriter(out, new XmlFriendlyNameCoder("__", "_"));
			}
		});
}
 
Example 29
Source Project: lams   Source File: Dom4JDriver.java    License: GNU General Public License v2.0 5 votes vote down vote up
public HierarchicalStreamWriter createWriter(final Writer out) {
    final HierarchicalStreamWriter[] writer = new HierarchicalStreamWriter[1];
    final FilterWriter filter = new FilterWriter(out){
        public void close() {
            writer[0].close();
        }
    };
    writer[0] = new Dom4JXmlWriter(new XMLWriter(filter,  outputFormat), getNameCoder());
    return writer[0];
}
 
Example 30
Source Project: lams   Source File: MapConverter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
    Map map = (Map) source;
    String entryName = mapper().serializedClass(Map.Entry.class);
    for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
        Map.Entry entry = (Map.Entry) iterator.next();
        ExtendedHierarchicalStreamWriterHelper.startNode(writer, entryName, entry.getClass());

        writeCompleteItem(entry.getKey(), context, writer);
        writeCompleteItem(entry.getValue(), context, writer);

        writer.endNode();
    }
}