simple-support Mailing List for Simple (Page 11)
Brought to you by:
niallg
You can subscribe to this list here.
| 2007 |
Jan
|
Feb
(2) |
Mar
(2) |
Apr
(13) |
May
(13) |
Jun
(27) |
Jul
(4) |
Aug
(14) |
Sep
(7) |
Oct
|
Nov
(6) |
Dec
(24) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2008 |
Jan
|
Feb
(21) |
Mar
(10) |
Apr
(15) |
May
(24) |
Jun
(24) |
Jul
(30) |
Aug
(5) |
Sep
(19) |
Oct
(27) |
Nov
(16) |
Dec
(24) |
| 2009 |
Jan
(34) |
Feb
(24) |
Mar
(35) |
Apr
(26) |
May
(8) |
Jun
(17) |
Jul
(28) |
Aug
(31) |
Sep
(36) |
Oct
(35) |
Nov
(20) |
Dec
(16) |
| 2010 |
Jan
(40) |
Feb
(21) |
Mar
(47) |
Apr
(45) |
May
(34) |
Jun
(68) |
Jul
(46) |
Aug
(39) |
Sep
(47) |
Oct
(20) |
Nov
(42) |
Dec
(13) |
| 2011 |
Jan
(41) |
Feb
(16) |
Mar
(32) |
Apr
(44) |
May
(28) |
Jun
(35) |
Jul
(37) |
Aug
(33) |
Sep
(60) |
Oct
(20) |
Nov
(35) |
Dec
(23) |
| 2012 |
Jan
(34) |
Feb
(23) |
Mar
(34) |
Apr
(21) |
May
(48) |
Jun
(24) |
Jul
(31) |
Aug
(39) |
Sep
(25) |
Oct
(10) |
Nov
(27) |
Dec
(28) |
| 2013 |
Jan
(32) |
Feb
(24) |
Mar
(24) |
Apr
(9) |
May
(4) |
Jun
(6) |
Jul
(2) |
Aug
(5) |
Sep
|
Oct
(5) |
Nov
(1) |
Dec
(12) |
| 2014 |
Jan
(14) |
Feb
(16) |
Mar
(5) |
Apr
(3) |
May
(2) |
Jun
(8) |
Jul
(2) |
Aug
|
Sep
(6) |
Oct
|
Nov
(6) |
Dec
|
| 2015 |
Jan
(3) |
Feb
(15) |
Mar
(7) |
Apr
|
May
|
Jun
(1) |
Jul
|
Aug
|
Sep
(2) |
Oct
|
Nov
|
Dec
(1) |
| 2016 |
Jan
|
Feb
(6) |
Mar
(2) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
| 2017 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
(1) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
| 2018 |
Jan
(1) |
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(1) |
Dec
|
| 2019 |
Jan
|
Feb
|
Mar
|
Apr
(1) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
|
From: Chris J. <ch...@gm...> - 2012-11-29 20:46:56
|
simpleframework ElementException: Element subscriber does not have a match
in class com.xyz.dazzler3.model.SubscribersList at line 1
I'm invoking this with:
*SubscribersList response = serializer.read(SubscribersList.class,
newStringReader(XMLString));
*
...where XMLString is the xml I'm reading.
I'm using @ElementList to define the List of Subscribers and I have a class
to define each individual subscriber. Seems it should be "simple", but I'm
not seeing what is wrong.
I have tried variations on the entry attribute, but nothing seems to work.
Anyone see my glaring error?
simple-xml-2.6.7.jar in my libs dir.
Thanks for any help/tips,
Chris.
*The Subscribers object (note plural):*
package com. xyz.dazzler3.model;
import java.util.List;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
@Root(name="subscribers")
public class SubscribersList {
@ElementList(entry="Subscriber", inline=true)
private List<Subscriber> list;
public List<Subscriber> getList() {
return list;
}
public void setList(List<Subscriber> list) {
this.list = list;
}
}
*The Subscriber Object:*
package com. xyz.dazzler3.model;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
@Root(name="subscriber")
public class Subscriber {
@Element(name="id")
private String id;
@Element(name="fname")
private String fname;
@Element(name="lname"
private String lname;
@Element(name="phone")
private String phone;
@Element(name="countryISO")
private String countryISO;
@Element(name="mac", required=false)
private String mac;
@Element(name="evid")
private String evid;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCountryISO() {
return countryISO;
}
public void setCountryISO(String countryISO) {
this.countryISO = countryISO;
}
public String getMac() {
return mac;
}
public void setMac(String mac) {
this.mac = mac;
}
public String getEvid() {
return evid;
}
public void setEvid(String evid) {
this.evid = evid;
}
}
*Sample XML:*
<?xml version="1.0" encoding="utf-8"?>
<subscribers>
<subscriber>
<id>1234567890</id>
<fname>Roberto</fname>
<lname>Jackson</lname>
<phone>510-419-2204</phone>
<countryISO>USA</countryISO>
<mac></mac>
<evid>1234567890</evid>
</subscriber>
<subscriber>
<id>4567890123</id>
<fname>Paul</fname>
<lname>Fults</lname>
<phone>201-433-5674</phone>
<countryISO>USA</countryISO>
<mac></mac>
<evid>4567890123</evid>
</subscriber>
</subscribers>
|
|
From: Lecomte, J-F. <JFL...@rh...> - 2012-11-29 01:15:16
|
I get a < NoSuchMethodException > when I try to serialize a list that is wrapped by Collections.unmodifiableList(...) or a list obtained by Arrays.asList(...). The same applies to UnmodifiableList from Google's Guava library.
Here is a snippet that exposes the problem:
public class Main
{
public static void main(final String[] args) throws Exception
{
final ArrayList<Integer> arrayList = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4));
testLoadSave(new ObjectToPersist(arrayList)); // Will be successful
testLoadSave(new ObjectToPersist(Collections.unmodifiableList(arrayList))); // Will throw a NoSuchMethodException
testLoadSave(new ObjectToPersist(Arrays.asList(5, 6, 7, 8)));
}
private static void testLoadSave(final ObjectToPersist objectToPersist) throws Exception
{
final Serializer serializer = new Persister();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
serializer.write(objectToPersist, out);
final ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
final ObjectToPersist objectRead = serializer.read(ObjectToPersist.class, in);
System.out.println(objectRead);
}
public static class ObjectToPersist
{
@ElementList(name = "myList", entry = "element")
private final List<Integer> _myList;
public ObjectToPersist(
@ElementList(name = "myList", entry = "element") final List<Integer> myList)
{
_myList = myList;
}
public List<Integer> getMyList()
{
return _myList;
}
@Override
public String toString()
{
final StringBuilder builder = new StringBuilder();
builder.append("ObjectToPersist@");
builder.append(hashCode());
builder.append("[_myList=");
builder.append(_myList);
builder.append("]");
return builder.toString();
}
}
}
I don't really care about the exact type of the list stored in my object, but I would like to keep it unmodifiable. So far I fixed the problem by modifying "ObjectToPersist" class this way:
public ObjectToPersist(
@ElementList(name = "myList", entry = "element") final List<Integer> myList)
{
_myList = new ArrayList<Integer>(myList);
}
public List<Integer> getMyList()
{
return Collections.unmodifiableList(_myList);
}
But this implies creating a new ArrayList all the time. I would prefer something like this:
public ObjectToPersist(
@ElementList(name = "myList", entry = "element") final List<Integer> myList)
{
if (myList is already immutable)
_myList = myList;
else
_myList = new ArrayList<Integer>(myList);
}
public List<Integer> getMyList()
{
return _myList;
}
Using ImmutableList from Google's Guava library, I could do just this (ImmutableList.copyOf(...)), but it won't serialize... I was wondering if there was a way to support those immutable collections with SimpleXML...
Thanks!
JFL
|
|
From: Niall G. - Y. <Nia...@yi...> - 2012-11-28 22:26:09
|
Hi Jochen,
I am afraid I do not understand the question, can you put this in a test case with some asserts, then perhaps I can figure out what you are trying to do.
Thanks,
Niall
From: jo...@va... [mailto:jo...@va...]
Sent: Thursday, 29 November 2012 1:34 AM
To: sim...@li...
Subject: [Simple-support] @ElementMap
----- Forwarded message -----
From: "van Waasen Jochen (KFSC 11)" <joc...@cr...<mailto:joc...@cr...>>
To: <sim...@li...<mailto:sim...@li...>>
Cc: <jo...@va...<mailto:jo...@va...>>
Subject: @ElementMap
Date: Wed, Nov 28, 2012 15:17
Hi,
I am new to simpleXML and stuck with @ElementMap.
I would like to parse the following:
<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.5">
<dict>
<key>key01</key><string>value01</string>
<key>key02</key><string>value02</string>
<key>key03</key><string>value03</string>
</dict>
</plist>
My class looks like this:
import java.util.Map;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
@Root(name = "plist")
public class PropertyList{
@ElementMap(name = "dict",
key="key", keyType=String.class,
value="string", valueType=String.class,
required=false, inline=false)
private Map<String, String> plDictionary;
@Attribute(required = true)
private String version;
public String getVersion(){
return this.version;
}
public Map<String, String> getMap(){
return this.plDictionary;
}
public void setMap(Map<String, String> theMap){
this.plDictionary = theMap;
}
}
As a result I get a Map which contains another Map with null values.
I would expect only ONE Map to be created.
If I change the XML to this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.5">
<dict>
<dict>
<key>key01</key><string>value01</string>
<key>key02</key><string>value02</string>
<key>key03</key><string>value03</string>
</dict>
</dict>
</plist>
Then the Map inside the Map has the values.
What is wrong in my config? I just want to have ONE Map that holds these values.
How can this be achieved?
Thanks
Jochen
|
|
From: <jo...@va...> - 2012-11-28 14:51:36
|
----- Forwarded message -----
From: "van Waasen Jochen (KFSC 11)" <joc...@cr...>
To: <sim...@li...>
Cc: <jo...@va...>
Subject: @ElementMap
Date: Wed, Nov 28, 2012 15:17
Hi, I am new to simpleXML and stuck with @ElementMap. I would like to parse the following: <?xml version="1.0" encoding="UTF-8"?><plist version="1.5"> <dict> <key>key01</key><string>value01</string> <key>key02</key><string>value02</string> <key>key03</key><string>value03</string> </dict></plist> My class looks like this: import java.util.Map; import org.simpleframework.xml.Attribute;import org.simpleframework.xml.ElementMap;import org.simpleframework.xml.Root; @Root(name = "plist")public class PropertyList{ @ElementMap(name = "dict", key="key", keyType=String.class, value="string", valueType=String.class, required=false, inline=false) private Map<String, String> plDictionary; @Attribute(required = true) private String version; public String getVersion(){ return this.version; } public Map<String, String> getMap(){ return this.plDictionary; } public void setMap(Map<String, String> theMap){ this.plDictionary = theMap; }} As a result I get a Map which contains another Map with null values.I would expect only ONE Map to be created. If I change the XML to this:<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.5"> <dict> <dict> <key>key01</key><string>value01</string> <key>key02</key><string>value02</string> <key>key03</key><string>value03</string></dict> </dict></plist> Then the Map inside the Map has the values. What is wrong in my config? I just want to have ONE Map that holds these values.How can this be achieved? ThanksJochen |
|
From: Niall G. - Y. <Nia...@yi...> - 2012-11-26 22:17:31
|
Interesting, I will take a look at this. I have never annotated an enum in this way, however I do not see a problem with processing enums in this manner if there is an @Root annotation on it. I am sure this is just a minor change, ill be releasing a new version soon, if its reasonable to do so Ill add back support for serializing enums in this way.
From: Kiran Rao [mailto:tec...@gm...]
Sent: Monday, 26 November 2012 9:38 PM
To: sim...@li...
Subject: [Simple-support] Simple 2.6.7 doesn't handle enums in the same way as Simple 2.6 does?
Consider the following enun:
@Root(name="days")
public enum DaysOfWeek {
SUNDAY("blue", 30),
MONDAY("green", 60),
TUESDAY("yellow", 50),
WEDNESDAY("red", 45),
THURSDAY("black", 45),
FRIDAY("white", 65),
SATURDAY("brown", 40);
@Attribute(name="color")
private String color;
@Element(name="mins")
private int minutes;
DaysOfWeek(String color, int minutes){
this.color = color;
this.minutes = minutes;
}
DaysOfWeek(){
/*
* Default constructor
*/
}
public void setColor(String color){
this.color = color;
}
public void setMinutes(int minutes){
this.minutes = minutes;
}
public String getColor(){
return this.color;
}
public int getMinutes(){
return this.minutes;
}
}
And, the code to serialize it:
StringWriter writer = new StringWriter();
try {
serializer.write(DaysOfWeek.TUESDAY, writer);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(writer.toString());
With simple-2.6, I see this output - which is what I expect:
<days color="yellow">
<mins>50</mins>
</days>
However, the *same* code, when serialized with simple-2.6.7, gives this:
<daysOfWeek>TUESDAY</daysOfWeek>
Basically, in simple-2.6.7, the individual members of an enum (and the simple-xml annotations on them) are ignored and always the name of the enum constant is used for serialization.
Is this intended? How do I get the latest version of simple-xml to serialize an enum while taking the individual members of the enum into consideration?
--
Regards,
=======
Kiran Rao
http://curioustechizen.blogspot.com/
http://stackoverflow.com/users/570930/curioustechizen
|
|
From: Kiran R. <tec...@gm...> - 2012-11-26 10:37:49
|
Consider the following enun:
@Root(name="days")
public enum DaysOfWeek {
SUNDAY("blue", 30),
MONDAY("green", 60),
TUESDAY("yellow", 50),
WEDNESDAY("red", 45),
THURSDAY("black", 45),
FRIDAY("white", 65),
SATURDAY("brown", 40);
@Attribute(name="color")
private String color;
@Element(name="mins")
private int minutes;
DaysOfWeek(String color, int minutes){
this.color = color;
this.minutes = minutes;
}
DaysOfWeek(){
/*
* Default constructor
*/
}
public void setColor(String color){
this.color = color;
}
public void setMinutes(int minutes){
this.minutes = minutes;
}
public String getColor(){
return this.color;
}
public int getMinutes(){
return this.minutes;
}
}
And, the code to serialize it:
StringWriter writer = new StringWriter();
try {
serializer.write(DaysOfWeek.TUESDAY, writer);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(writer.toString());
With simple-2.6, I see this output - which is what I expect:
<days color="yellow">
<mins>50</mins>
</days>
However, the *same* code, when serialized with simple-2.6.7, gives this:
<daysOfWeek>TUESDAY</daysOfWeek>
Basically, in simple-2.6.7, the individual members of an enum (and the
simple-xml annotations on them) are ignored and always the name of the enum
constant is used for serialization.
Is this intended? How do I get the latest version of simple-xml to
serialize an enum while taking the individual members of the enum into
consideration?
--
Regards,
=======
Kiran Rao
http://curioustechizen.blogspot.com/
http://stackoverflow.com/users/570930/curioustechizen
|
|
From: moonlightcheese <moo...@gm...> - 2012-11-22 18:53:27
|
Dennis Bijwaard-2 wrote: > > The script works as follows (tested on Ubuntu Linux): > - generate source with xjc: xjc XMLSchema.xsd > - jaxb2simple.sed generated/JAXBSource.java > > src/generated/SimpleSource.java > - or in batch with the rewrite script: > NAMESPACE=generated > cd $NAMESPACE > for i in *.java ;do ../../rewrite.sh $i ../$NAMESPACE/ddi/$i ;done > > #!/bin/sed -f > # jaxb2simple.sed September 2011 > # > # Copyright (C) 2011, Dennis Bijwaard <bij...@gm...> > # > # Licensed under the Apache License, Version 2.0 (the "License"); > # you may not use this file except in compliance with the License. > # You may obtain a copy of the License at > # > # http://www.apache.org/licenses/LICENSE-2.0 > # > # Unless required by applicable law or agreed to in writing, software > # distributed under the License is distributed on an "AS IS" BASIS, > # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or > # implied. See the License for the specific language governing > # permissions and limitations under the License. > > # note that simpleframework requires everything (elements/attributes) > # by default, so required=false is often necessary > > # UPDATE PACKAGE NAME, ADJUST WHEN NEEDED > #s/^package generated;/package com.example;/ > # change jaxb imports to generic simpleframework one > /import javax.xml.bind.annotation\./N > /import javax.xml.bind.annotation\./N > /import javax.xml.bind.annotation\./N > /import javax.xml.bind.annotation\./N > /import javax.xml.bind.annotation\./N > s/^\(import javax.xml.bind.annotation.\w*;\n\)*import > javax.xml.bind.annotation.\w*;/import org.simpleframework.xml.*;/ > # change @XmlRootElement to @Root > s/@XmlRootElement(\(.*\))/@Root(\1, strict=false)/ > # change @XmlElement with list to @ElementList > /@XmlElement/{ N > s/@XmlElement(name[ > ]*=\(.*\)).*\(\n.*List\<.*\>.*;\)/@ElementList(inline=true, entry=\1)\2/ > s/@XmlElement(\(.*required.*\))/@Element(\1)/ > s/@XmlElement(\(.*\))/@Element(required=false,\1)/ > } > # change ordered items to @Order > s/@XmlType(.*propOrder[ ]*\(=.*\)/@Order(elements\1/ > # change @XmlAttribute to @Attribute > s/@XmlAttribute(\(.*required\)/@Attribute(\1/ > s/@XmlAttribute(/@Attribute(required=false,/ > s/@XmlAttribute/@Attribute(required=false)/ > # change XmlAccessorType+@XmlType to @Root, but with propOrder to @Order > /@XmlAccessorType/{ N > s/@XmlAccessorType([ > ]*XmlAccessType\.\(.*\))\n@XmlType(\(.*\))/@Default(DefaultType.\1)\n@Root(\2, > strict=false)/ > s/@XmlAccessorType([ ]*XmlAccessType\.\(.*\))\n@XmlType(\(.*\)[ ]*,[ > ]*propOrder[ ]*\(=.*\)/@Default(DefaultType.\1)\n@Order(elements\3/ > } > #s/@XmlAccessorType([ ]*XmlAccessType\.\(.*\))/@Default(DefaultType.\1)/ > s/@XmlAccessorType([ ]*XmlAccessType\.\(.*\))/@Default(DefaultType.\1)/ > s/@XmlType([ ]*name[ ]*=\(.*\))/@Root(name=\1, strict=false)/ > /@XmlEnum/D > /@XmlRegistry/D > did you actually test this? running: ../jaxb2simple.sed [filename] > simple/[filename] from 'generated' dir on Ubuntu Linux generates: : No such file or directorye this doesn't work at all. seems like sed is failing? no clue. (i know this thread is old, but there are no tools at all built for this purpose that i could find. you would think someone would have written something for Simple by now that generates classes from .xsd files, but it hasn't happened yet.) -- View this message in context: http://old.nabble.com/xjc-created-jaxb-source-from-XML-schema-to-simpleframework-tp32442003p34711894.html Sent from the Simple XML Serialization mailing list archive at Nabble.com. |
|
From: Niall G. <gal...@ya...> - 2012-11-21 10:19:51
|
There is no problem here, ignore the error. It is doing exactly what it is supposed to do StAX does not come with Android, it will failover to XmlPull.
You need to ignore the log. If you think there is a problem you will need to explain what the problem is.
--- On Wed, 21/11/12, Mihael Schmidt <msc...@sg...> wrote:
> From: Mihael Schmidt <msc...@sg...>
> Subject: [Simple-support] Simple Xml 2.6.6 on Android device fails
> To: sim...@li...
> Received: Wednesday, 21 November, 2012, 12:22 AM
>
>
>
>
>
>
> Hi,
>
>
>
> first thanx for the great xml library. Good job.
>
>
>
> But now I am facing a little problem. A REST web service
> returns an
> object (xml) from a POST call. The call succeeds but
> when getting
> the object from the response body I am getting an
> error.
>
>
>
>
> HttpComponentsClientHttpRequestFactory requestFactory =
> createHttpRequestFactory(context);
>
>
> RestTemplate restTemplate = new
> RestTemplate(requestFactory);
>
>
> restTemplate.getMessageConverters().add(new
> SimpleXmlHttpMessageConverter());
>
> try {
>
>
>
> ResponseEntity<Interessent> response =
> restTemplate.postForEntity(new URI(url), prospect,
> Interessent.class);
>
>
>
>
>
>
>
> return response.getBody(); /// <--- here it
> fails
>
> }
>
>
> catch(Exception e) {
>
>
>
> Log.e(ProspectService.class.getName(), "Error on rest
> call. " + e.getClass().getName() + ": "
> +
> e.getLocalizedMessage());
>
>
>
> return null;
>
> }
>
>
>
> Output:
>
>
>
> 11-21 09:09:06.121: I/dalvikvm(27169): Could not find
> method
> javax.xml.stream.XMLInputFactory.newInstance,
> referenced from
> method
> org.simpleframework.xml.stream.StreamProvider.<init>
>
> 11-21 09:09:06.121: W/dalvikvm(27169): VFY: unable to
> resolve
> static method 1021:
> Ljavax/xml/stream/XMLInputFactory;.newInstance
> ()Ljavax/xml/stream/XMLInputFactory;
>
> 11-21 09:09:06.121: D/dalvikvm(27169): VFY: replacing
> opcode 0x71
> at 0x0003
>
> 11-21 09:09:06.121: W/dalvikvm(27169): VFY: unable to
> find class
> referenced in signature
> (Ljavax/xml/stream/XMLEventReader;)
>
> 11-21 09:09:06.125: W/dalvikvm(27169): VFY: unable to
> find class
> referenced in signature
> (Ljavax/xml/stream/XMLEventReader;)
>
> 11-21 09:09:06.125: I/dalvikvm(27169): Could not find
> method
> javax.xml.stream.XMLInputFactory.createXMLEventReader,
> referenced
> from method
> org.simpleframework.xml.stream.StreamProvider.provide
>
> 11-21 09:09:06.125: W/dalvikvm(27169): VFY: unable to
> resolve
> virtual method 1019:
>
> Ljavax/xml/stream/XMLInputFactory;.createXMLEventReader
>
> (Ljava/io/InputStream;)Ljavax/xml/stream/XMLEventReader;
>
> 11-21 09:09:06.125: D/dalvikvm(27169): VFY: replacing
> opcode 0x6e
> at 0x0002
>
> 11-21 09:09:06.125: I/dalvikvm(27169): Could not find
> method
> javax.xml.stream.XMLInputFactory.createXMLEventReader,
> referenced
> from method
> org.simpleframework.xml.stream.StreamProvider.provide
>
> 11-21 09:09:06.125: W/dalvikvm(27169): VFY: unable to
> resolve
> virtual method 1020:
>
> Ljavax/xml/stream/XMLInputFactory;.createXMLEventReader
>
> (Ljava/io/Reader;)Ljavax/xml/stream/XMLEventReader;
>
>
>
> I am using RestTemplate 1.0.0.RC1 and Simple XML 2.6.6.
>
>
>
> The weirdest thing is that it works on the Android
> emulator (tested
> Android 3.2 and 4.2) and it fails on a real smartphone
> (Android
> 4.1.2).
>
>
>
> What is also weird is that if I debug the app I can see
> the correct
> values in the response object.
>
>
>
> Any ideas?
>
>
>
> Thanx in advance.
>
>
>
> Regards
>
>
>
> Mihael
>
>
>
>
>
>
> Schulz Gebäudeservice GmbH & Co.
> KGDr.-Max-Ilgner-Straße
> 1732339
> EspelkampPersönlich haftende
> Gesellschafterin:Gebäudereinigung Joachim
> SchulzVerwaltungsgesellschaft
> mbHTelefon: +49 5772 9100
> 0Telefax: +49
> 5772 9100 11Email: zen...@sg...: www.sgbs.deGeschäftsführer: Joachim und Dirk Schulz,
> Norbert KosicaHandelsregister Bad Oeynhausen: HRA 5902, HRB
> 8591UST-Id-Nr.: DE
> 125752702
> -----Inline Attachment Follows-----
>
> ------------------------------------------------------------------------------
> Monitor your physical, virtual and cloud infrastructure from
> a single
> web console. Get in-depth insight into apps, servers,
> databases, vmware,
> SAP, cloud infrastructure, etc. Download 30-day Free Trial.
> Pricing starts from $795 for 25 servers or applications!
> http://p.sf.net/sfu/zoho_dev2dev_nov
> -----Inline Attachment Follows-----
>
> _______________________________________________
> Simple-support mailing list
> Sim...@li...
> https://lists.sourceforge.net/lists/listinfo/simple-support
>
|
|
From: Mihael S. <msc...@sg...> - 2012-11-21 08:50:19
|
Hi,
first thanx for the great xml library. Good job.
But now I am facing a little problem. A REST web service returns an
object (xml) from a POST call. The call succeeds but when getting the
object from the response body I am getting an error.
HttpComponentsClientHttpRequestFactory requestFactory =
createHttpRequestFactory(context);
RestTemplate restTemplate = new RestTemplate(requestFactory);
restTemplate.getMessageConverters().add(new
SimpleXmlHttpMessageConverter());
try {
ResponseEntity<Interessent> response =
restTemplate.postForEntity(new URI(url), prospect, Interessent.class);
return response.getBody(); /// *<--- here it fails*
}
catch(Exception e) {
Log.e(ProspectService.class.getName(), "Error on rest call.
" + e.getClass().getName() + ": " + e.getLocalizedMessage());
return null;
}
Output:
11-21 09:09:06.121: I/dalvikvm(27169): Could not find method
javax.xml.stream.XMLInputFactory.newInstance, referenced from method
org.simpleframework.xml.stream.StreamProvider.<init>
11-21 09:09:06.121: W/dalvikvm(27169): VFY: unable to resolve static
method 1021: Ljavax/xml/stream/XMLInputFactory;.newInstance
()Ljavax/xml/stream/XMLInputFactory;
11-21 09:09:06.121: D/dalvikvm(27169): VFY: replacing opcode 0x71 at 0x0003
11-21 09:09:06.121: W/dalvikvm(27169): VFY: unable to find class
referenced in signature (Ljavax/xml/stream/XMLEventReader;)
11-21 09:09:06.125: W/dalvikvm(27169): VFY: unable to find class
referenced in signature (Ljavax/xml/stream/XMLEventReader;)
11-21 09:09:06.125: I/dalvikvm(27169): Could not find method
javax.xml.stream.XMLInputFactory.createXMLEventReader, referenced from
method org.simpleframework.xml.stream.StreamProvider.provide
11-21 09:09:06.125: W/dalvikvm(27169): VFY: unable to resolve virtual
method 1019: Ljavax/xml/stream/XMLInputFactory;.createXMLEventReader
(Ljava/io/InputStream;)Ljavax/xml/stream/XMLEventReader;
11-21 09:09:06.125: D/dalvikvm(27169): VFY: replacing opcode 0x6e at 0x0002
11-21 09:09:06.125: I/dalvikvm(27169): Could not find method
javax.xml.stream.XMLInputFactory.createXMLEventReader, referenced from
method org.simpleframework.xml.stream.StreamProvider.provide
11-21 09:09:06.125: W/dalvikvm(27169): VFY: unable to resolve virtual
method 1020: Ljavax/xml/stream/XMLInputFactory;.createXMLEventReader
(Ljava/io/Reader;)Ljavax/xml/stream/XMLEventReader;
I am using RestTemplate 1.0.0.RC1 and Simple XML 2.6.6.
The weirdest thing is that it works on the Android emulator (tested
Android 3.2 and 4.2) and it fails on a real smartphone (Android 4.1.2).
What is also weird is that if I debug the app I can see the correct
values in the response object.
Any ideas?
Thanx in advance.
Regards
Mihael
--
Schulz Gebäudeservice GmbH & Co. KG
Dr.-Max-Ilgner-Straße 17
32339 Espelkamp
Persönlich haftende Gesellschafterin:
Gebäudereinigung Joachim Schulz
Verwaltungsgesellschaft mbH
Telefon: +49 5772 9100 0
Telefax: +49 5772 9100 11
Email: zen...@sg...
Internet: www.sgbs.de
Geschäftsführer: Joachim und Dirk Schulz, Norbert Kosica
Handelsregister Bad Oeynhausen: HRA 5902, HRB 8591
UST-Id-Nr.: DE 125752702
|
|
From: Niall G. <gal...@ya...> - 2012-11-19 10:10:38
|
It works as I intended it to, feel free to refactor as you wish.
--- On Mon, 19/11/12, Christian Klotz <c....@sp...> wrote:
> From: Christian Klotz <c....@sp...>
> Subject: Re: [Simple-support] Serialize and deserialize undefined Xml attributes into a HashMap<String, String>
> To: "Niall Gallagher" <gal...@ya...>
> Cc: "Niall Gallagher - Yieldbroker" <Nia...@yi...>, "sim...@li..." <sim...@li...>
> Received: Monday, 19 November, 2012, 1:31 AM
>
>
>
>
>
>
> Hi Naill,
>
>
>
> you do a great job.
>
>
>
> But the converter works not correctly.
>
>
>
> The read method fill all attributes of the SOURCE Xml
> into the
> hashmap "furtherAttributes" as you can see
> on the screen shot.
>
> So I have added 4 asserts to your test case and they
> fail.
>
>
>
> Only because of that "error" the write
> method works.
>
> Only the further attributes are written out and not of
> the normal
> attributes.
>
>
>
> Your asserts "assertElementHasAttribute" do
> not throw an failure,
> because the read method filled the HashMap
>
> "car.furtherAttributes" with all five
> attributes.
>
>
>
>
>
>
>
>
>
> public void testConverter() throws Exception
>
> {
>
> Strategy
> strategy = new AnnotationStrategy();
>
> Serializer
> serializer = new Persister(strategy);
>
> StringWriter
> buffer = new StringWriter();
>
> Car car =
> serializer.read(Car.class, SOURCE, false);
>
>
>
>
> assertNotNull(car);
>
>
> assertEquals(car.length, 3.3);
>
>
> assertEquals(car.color, "green");
>
>
> assertEquals(car.nrOfDoors, 2);
>
>
> assertEquals(car.furtherAttributes.get("topSpeed"),
> "190");
>
>
> assertEquals(car.furtherAttributes.get("brand"),
> "audi");
>
>
>
> // Asserts by
> Christian
>
>
> assertEquals(car.furtherAttributes.size(), 2);
>
>
> assertEquals(car.furtherAttributes.containsKey("length"),
> false);
>
>
> assertEquals(car.furtherAttributes.containsKey("color"),
> false);
>
>
>
> assertEquals(car.furtherAttributes.containsKey("nrOfDoors"),
> false);
>
>
>
>
> serializer.write(car, System.out);
>
>
> serializer.write(car, buffer);
>
>
>
> String text =
> buffer.toString();
>
>
> assertElementExists(text, "/Car");
>
>
> assertElementHasAttribute(text, "/Car",
> "length", "3.3");
>
>
> assertElementHasAttribute(text, "/Car",
> "color", "green");
>
>
> assertElementHasAttribute(text, "/Car",
> "nrOfDoors", "2");
>
>
> assertElementHasAttribute(text, "/Car",
> "topSpeed",
> "190");
>
>
> assertElementHasAttribute(text, "/Car",
> "brand", "audi");
>
> }
>
>
>
>
>
> Thanks
>
>
>
> Christian
>
>
>
> Am 17.11.2012 04:03, schrieb Niall Gallagher:
>
>
>
> You are doing far too much work here, let the
> framework handle most of it. I normally would not do this,
> but since there is no good example in the test cases I have
> implemented it and added it here. I does your Car schema.
>
> https://niallg@simple.svn.sourceforge.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/DynamicMapOfAttributesTest.java
>
> --- On Fri, 16/11/12, Christian Klotz <c....@sp...>
> wrote:
>
>
>
> From: Christian Klotz <c....@sp...>
> Subject: Re: [Simple-support] Serialize and deserialize
> undefined Xml attributes into a HashMap<String,
> String>
> To: "Niall Gallagher - Yieldbroker" <Nia...@yi...>
> Cc: "sim...@li..."
> <sim...@li...>
> Received: Friday, 16 November, 2012, 9:41 AM
>
>
>
>
>
>
> Ah ok, thanks.
>
>
>
> Now I tried it with two converters.
>
>
>
> The first one is this:
>
> public class HashMapConverter implements
> Converter<HashMap<String, String>>
>
> {
>
> @Override
>
> public HashMap<String,
> String> read(InputNode node)
> throws Exception
>
> {
>
> // Is never
> called
>
> return null;
>
> }
>
>
>
> @Override
>
> public void write(OutputNode node,
> HashMap<String,
> String> hashMap)
>
>
> throws Exception
>
> {
>
> OutputNode
> parent = node.getParent();
>
>
>
> for
> (Entry<String, String> entry :
> hashMap.entrySet())
>
> {
>
>
> //Does not work
>
>
> parent.setAttribute(entry.getKey(),
> entry.getValue());
>
> }
>
>
>
> node.remove();
>
> }
>
> }
>
>
>
> This is the car class:
>
> @Root(strict = false, name = "Car")
>
> public class Car
>
> {
>
> @Attribute
>
> public double length;
>
>
>
> @Attribute
>
> public String color;
>
>
>
> @Attribute
>
> public int nrOfDoors;
>
>
>
> @ElementMap(required = false)
>
> public HashMap<String,
> String> furtherAttributes;
>
> }
>
>
>
> And this how I set the converter. Set the converter by
> AnnotationStategy and @Convert never works.
>
> public void testCar() throws
> Exception
>
> {
>
> Car car = new
> Car();
>
> car.color =
> "red";
>
> car.length =
> 4.3;
>
> car.nrOfDoors =
> 4;
>
>
>
>
> car.furtherAttributes = new HashMap<String,
> String>();
>
>
> car.furtherAttributes.put("fuelConsumption",
> "7.8");
>
>
> car.furtherAttributes.put("fopSpeed",
> "190");
>
>
>
> Registry
> registry = new Registry();
>
> RegistryStrategy
> strategy = new
> RegistryStrategy(registry);
>
>
>
>
> registry.bind(HashMap.class, HashMapConverter.class);
>
>
> //registry.bind(Car.class, CarConverter.class);
>
>
>
> StringWriter
> stringwriter = new StringWriter();
>
> Serializer
> serializer = new Persister(strategy);
>
>
> serializer.write(car, stringwriter);
>
>
>
> String xml =
> stringwriter.toString();
>
> }
>
>
>
> But on this try, the read method of the converter is
> never called
> (There is not furtherAttributes xml element) and I
> can't set
> attributes on the parent node. (See comments in the
> HashMapConverter)
>
>
>
> The second try was a converter for the car class:
>
> public class CarConverter implements
> Converter<Car>
>
> {
>
> @Override
>
> public Car read(InputNode node)
> throws Exception
>
> {
>
> Car car = new
> Car();
>
>
> car.furtherAttributes = new HashMap<String,
> String>();
>
>
>
>
> ArrayList<String> attributesWithAnnotation = new
> ArrayList<String>();
>
> for (Field field
> : car.getClass().getFields())
>
> {
>
>
> if (field.getAnnotation(Attribute.class)
> != null)
>
>
> {
>
>
> String name =
> field.getAnnotation(Attribute.class).name();
>
>
>
>
> if (name == null ||
> name.equals(""))
>
>
> {
>
>
>
> name = field.getName();
>
>
> }
>
>
>
>
>
> attributesWithAnnotation.add(name);
>
>
> }
>
> }
>
>
>
> for (String
> entry : node.getAttributes())
>
> {
>
>
> if
> (!attributesWithAnnotation.contains(entry))
>
>
> {
>
>
> String
> furtherAttributeKey = entry;
>
>
> String
> furtherAttributeValue =
> node.getAttribute(entry)
>
>
>
> .getValue();
>
>
>
>
>
> car.furtherAttributes.put(furtherAttributeKey,
>
>
>
> furtherAttributeValue);
>
>
> }
>
> }
>
>
>
> return car;
>
> }
>
>
>
> @Override
>
> public void write(OutputNode
> outputNode, Car car) throws
> Exception
>
> {
>
> if
> (car.furtherAttributes != null &&
> car.furtherAttributes.size() > 0)
>
> {
>
>
> for (Entry<String, String> entry :
> car.furtherAttributes.entrySet())
>
>
> {
>
>
>
> outputNode.setAttribute(entry.getKey(),
> entry.getValue());
>
>
> }
>
> }
>
> }
>
> }
>
>
>
> But there is the problem that only futherAttributes
> are serialised
> and deserialised correctly.
>
> In the read method I create the car object myself. So
> color,
> length and the other field have the default value.
>
> But I want, that all that fields are filled by
> SimpleXml.
>
>
>
> What converter do you recommend?
>
>
>
>
>
> Am 15.11.2012 23:45, schrieb Niall Gallagher -
> Yieldbroker:
>
>
>
> Sorry, my mistake I should have suggested a
> converter. Here you can use @Convert annotation like so.
>
> @Convert(CarConverter.class)
> Map<String, String> var;
>
> Take a look at the following converters
>
> https://simple.svn.sf.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/HideEnclosingConverterTest.java
> https://simple.svn.sf.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/ExampleConverters.java
>
>
> -----Original Message-----
> From: Christian Klotz [mailto:c....@sp...]
>
> Sent: Friday, 16 November 2012 12:28 AM
> To: Niall Gallagher - Yieldbroker
> Cc: sim...@li...
> Subject: Re: [Simple-support] Serialize and deserialize
> undefined Xml attributes into a HashMap<String,
> String>
>
> Hi Niall,
>
> thanks for your quick response.
>
>
> Now I have implemented an Visitor.
> In the read method, I can get a nodeMap with all xml
> attributes.
>
> I can also detect via refection which attributes have the
> annotation @Attribute.
> All other attributes should be stored in the HashMap
> "furtherAttributes".
>
> But I don't known how to put them into the HashMap
> "furtherAttributes".
> I do not have the resulting car object. Do you have any tip?
>
> public class AnyAttributesVisitor implements Visitor {
> @Override
> public void read(Type type, NodeMap<InputNode>
> nodeMap) throws Exception
> {
> // nodeMap contains all xml attributes of the car
> xml
> // Content is:
> // {color=attribute color='red',
> length=attribute length='4.3',
> // nrOfDoors=attribute nrOfDoors='4',
> fuelConsumption=attribute
> // fuelConsumption='7.8',
> topSpeed=attribute topSpeed='190'}
>
>
> //Detect attributes with Annotation @Attribute
> ArrayList<String> attributesWithAnnotation =
> new
> ArrayList<String>();
> for (Field field : type.getType().getFields())
> {
> if (field.getAnnotation(Attribute.class) !=
> null)
> {
> String name =
> field.getAnnotation(Attribute.class).name();
>
> if (name == null ||
> name.equals(""))
> {
> name = field.getName();
> }
>
> attributesWithAnnotation.add(name);
> }
> }
>
> for (String entry :
> nodeMap.getNode().getAttributes())
> {
> if (!attributesWithAnnotation.contains(entry))
> {
> String furtherAttributeKey = entry;
> String furtherAttributeValue =
> nodeMap.getNode()
> .getAttribute(entry).getValue();
>
> // TODO: Add Key and Value to the Hashmap
> furtherAttributes
>
> nodeMap.remove(furtherAttributeKey);
> }
> }
> }
>
> @Override
> public void write(Type type, NodeMap<OutputNode>
> nodeMap) throws
> Exception
> {
>
> }
> }
>
> This is my test case:
> public void testCarDeserialisation() throws Exception
> {
> String xml = "<Car
> color=\"red\"
> length=\"4.3\"
> nrOfDoors=\"4\"
> fuelConsumption=\"7.8\"
> topSpeed=\"190\" />";
>
> Serializer serializer = new Persister(new
> VisitorStrategy(
> new AnyAttributesVisitor()));
>
> Car car = serializer.read(Car.class, xml);
> }
>
> Thanks Christian
>
> Am 15.11.2012 00:33, schrieb Niall Gallagher - Yieldbroker:
>
>
> I think a Visitor would be simpler than a
> Strategy, there are many test cases doing this very thing.
> Just browse through them, I am sure you will find a
> template. You can browse them here http://simple.svn.sourceforge.net/viewvc/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/
>
> -----Original Message-----
> From: Christian Klotz [mailto:c....@sp...]
> Sent: Wednesday, 14 November 2012 8:26 PM
> To: sim...@li...
> Subject: [Simple-support] Serialize and deserialize
> undefined Xml attributes into a HashMap<String,
> String>
>
> Hi SimpleXml Team,
>
> I use SimpleXml frequently on android and it is great.
>
> Now I have a question how to do that job:
> All XML attributes that are not defined in the Java class
> with @Attribute should be serialized and deserialized into a
> HashMap<String,String>.
>
> Here is an example:
>
> This is out test class "Car"
>
> @Root(strict = false, name = "Car")
> public class Car
> {
> @Attribute
> public double length;
>
> @Attribute
> public String color;
>
> @Attribute
> public int nrOfDoors;
>
> public HashMap<String, String> furtherAttributes
> = new HashMap<String, String>(); }
>
> And this is the serialization test method:
> public void testCar() throws Exception
> {
> Car car = new Car();
>
> car.color = "red";
> car.length = 4.3;
> car.nrOfDoors = 4;
>
>
> car.furtherAttributes.put("fuelConsumption",
> "7.8");
> car.furtherAttributes.put("topSpeed",
> "190");
>
> Serializer serializer = new Persister();
> StringWriter stringwriter = new StringWriter();
> serializer.write(car, stringwriter);
>
> String xml = stringwriter.toString();
> }
>
>
> The result of the serialization is:
> <Car color="red" length="4.3"
> nrOfDoors="4"/>
>
> So the furtherAttributes of the HashMap are missing. The
> result should be:
> <Car color="red" length="4.3"
> nrOfDoors="4" fuelConsumption="7.8"
> topSpeed="190" />
>
> And the way back should also work:
> So if we have a xml like this:
> <Car color="green" length="3.3"
> nrOfDoors="2" topSpeed="190"
> brand="audi" /> After the deserialization the
> HashMap "furtherAttributes" should have the two
> undefined attributes "topSpeed" and
> "brand".
>
> I already read the mailing list and some SimpleXml test
> cases.
> So I try implement a new Strategy to solve that problem.
>
> The AnyAttributeRegistryStrategy looks for classes with
> annotation "AnyClass" and inside that class
> searches for the annotation "Any".
> The annotation "Any" is used to tag the HashMap,
> where the futher attributes should be serialized to.
>
> public class AnyAttributeRegistryStrategy extends
> RegistryStrategy {
> public AnyAttributeRegistryStrategy(Registry registry)
> {
> super(registry);
> }
>
> @Override
> public boolean write(Type type, Object value,
> NodeMap<OutputNode> node,
> @SuppressWarnings("rawtypes") Map
> map) throws Exception
> {
>
> if (value.getClass().getAnnotation(AnyClass.class)
> != null)
> {
> for (Field field :
> value.getClass().getFields())
> {
> if (field.getAnnotation(Any.class) !=
> null)
> {
> Object mapObject = field.get(value);
> if (mapObject instanceof Map<?,
> ?>)
> {
> Map<?, ?> keyValueMap =
> (Map<?, ?>) mapObject;
> for (Entry<?, ?>
> keyValuePair :
> keyValueMap.entrySet())
> {
> if (keyValuePair.getKey() !=
> null
> &&
> keyValuePair.getValue() != null)
> {
>
> node.getNode().setAttribute(
> keyValuePair.getKey().toString(),
> keyValuePair.getValue().toString());
> }
> }
>
> }
> }
> }
> }
>
> return super.write(type, value, node, map);
> }
> }
>
> And this is the Car class with the new annotations:
> @AnyClass
> @Root(strict = false, name = "Car")
> public class Car
> {
> @Attribute
> public double length;
>
> @Attribute
> public String color;
>
> @Attribute
> public int nrOfDoors;
>
> @Any
> public HashMap<String, String> furtherAttributes
> = new HashMap<String, String>(); }
>
> Now the serialisation of the class to xml works.
> But I do not have a correctly working solution for the
> deserialisation.
> Do you have any ideas?
>
> Thanks for you help
>
> Christian Klotz
>
>
>
>
>
>
> ------------------------------------------------------------------------------
> Monitor your physical, virtual and cloud infrastructure from
> a single web console. Get in-depth insight into apps,
> servers, databases, vmware, SAP, cloud infrastructure, etc.
> Download 30-day Free Trial.
> Pricing starts from $795 for 25 servers or applications!
> http://p.sf.net/sfu/zoho_dev2dev_nov
> _______________________________________________
> Simple-support mailing list
> Sim...@li...
> https://lists.sourceforge.net/lists/listinfo/simple-support
>
>
>
>
>
>
>
>
>
>
>
> --
> Mit freundlichen Grüßen / Kind regards
>
> Christian Klotz
> Software Engineer
>
>
> SPEDION GmbH
> Industriestraße 7
> D - 63829 Krombach
> Fon: +49 (0) 6024 / 50990-132
> Fax: +49 (0) 6024 / 50990-121
> mailto:c....@sp...
>
> SPEDION GmbH - Industriestraße 7 - 63829 Krombach -
> Germany
> Amtsgericht Aschaffenburg, HRB 8647
> Geschäftsführer: Günter Englert, Wolfram
> Grohse
>
>
>
>
> -----Inline Attachment Follows-----
>
> ------------------------------------------------------------------------------
> Monitor your physical, virtual and cloud infrastructure from
> a single
> web console. Get in-depth insight into apps, servers,
> databases, vmware,
> SAP, cloud infrastructure, etc. Download 30-day Free Trial.
> Pricing starts from $795 for 25 servers or applications!
> http://p.sf.net/sfu/zoho_dev2dev_nov
> -----Inline Attachment Follows-----
>
> _______________________________________________
> Simple-support mailing list
> Sim...@li...
> https://lists.sourceforge.net/lists/listinfo/simple-support
>
>
>
>
>
>
>
>
>
>
> --
> Mit freundlichen Grüßen / Kind regards
>
> Christian Klotz
> Software Engineer
>
>
> SPEDION GmbH
> Industriestraße 7
> D - 63829 Krombach
> Fon: +49 (0) 6024 / 50990-132
> Fax: +49 (0) 6024 / 50990-121
> mailto:c....@sp...
>
> SPEDION GmbH - Industriestraße 7 - 63829 Krombach -
> Germany
> Amtsgericht Aschaffenburg, HRB 8647
> Geschäftsführer: Günter Englert, Wolfram
> Grohse
>
>
>
>
|
|
From: Christian K. <c....@sp...> - 2012-11-19 09:31:39
|
Hi Naill,
you do a great job.
But the converter works not correctly.
The read method fill all attributes of the SOURCE Xml into the hashmap
"furtherAttributes" as you can see on the screen shot.
So I have added 4 asserts to your test case and they fail.
Only because of that "error" the write method works.
Only the further attributes are written out and not of the normal
attributes.
Your asserts "assertElementHasAttribute" do not throw an failure,
because the read method filled the HashMap
"car.furtherAttributes" with all five attributes.
public void testConverter() throws Exception
{
Strategy strategy = new AnnotationStrategy();
Serializer serializer = new Persister(strategy);
StringWriter buffer = new StringWriter();
Car car = serializer.read(Car.class, SOURCE, false);
assertNotNull(car);
assertEquals(car.length, 3.3);
assertEquals(car.color, "green");
assertEquals(car.nrOfDoors, 2);
assertEquals(car.furtherAttributes.get("topSpeed"), "190");
assertEquals(car.furtherAttributes.get("brand"), "audi");
// Asserts by Christian
assertEquals(car.furtherAttributes.size(), 2);
assertEquals(car.furtherAttributes.containsKey("length"), false);
assertEquals(car.furtherAttributes.containsKey("color"), false);
assertEquals(car.furtherAttributes.containsKey("nrOfDoors"), false);
serializer.write(car, System.out);
serializer.write(car, buffer);
String text = buffer.toString();
assertElementExists(text, "/Car");
assertElementHasAttribute(text, "/Car", "length", "3.3");
assertElementHasAttribute(text, "/Car", "color", "green");
assertElementHasAttribute(text, "/Car", "nrOfDoors", "2");
assertElementHasAttribute(text, "/Car", "topSpeed", "190");
assertElementHasAttribute(text, "/Car", "brand", "audi");
}
Thanks
Christian
Am 17.11.2012 04:03, schrieb Niall Gallagher:
> You are doing far too much work here, let the framework handle most of it. I normally would not do this, but since there is no good example in the test cases I have implemented it and added it here. I does your Car schema.
>
> https://niallg@simple.svn.sourceforge.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/DynamicMapOfAttributesTest.java
>
> --- On Fri, 16/11/12, Christian Klotz <c....@sp...> wrote:
>
>> From: Christian Klotz <c....@sp...>
>> Subject: Re: [Simple-support] Serialize and deserialize undefined Xml attributes into a HashMap<String, String>
>> To: "Niall Gallagher - Yieldbroker" <Nia...@yi...>
>> Cc: "sim...@li..." <sim...@li...>
>> Received: Friday, 16 November, 2012, 9:41 AM
>>
>>
>>
>>
>>
>>
>> Ah ok, thanks.
>>
>>
>>
>> Now I tried it with two converters.
>>
>>
>>
>> The first one is this:
>>
>> public class HashMapConverter implements
>> Converter<HashMap<String, String>>
>>
>> {
>>
>> @Override
>>
>> public HashMap<String,
>> String> read(InputNode node)
>> throws Exception
>>
>> {
>>
>> // Is never
>> called
>>
>> return null;
>>
>> }
>>
>>
>>
>> @Override
>>
>> public void write(OutputNode node,
>> HashMap<String,
>> String> hashMap)
>>
>>
>> throws Exception
>>
>> {
>>
>> OutputNode
>> parent = node.getParent();
>>
>>
>>
>> for
>> (Entry<String, String> entry :
>> hashMap.entrySet())
>>
>> {
>>
>>
>> //Does not work
>>
>>
>> parent.setAttribute(entry.getKey(),
>> entry.getValue());
>>
>> }
>>
>>
>>
>> node.remove();
>>
>> }
>>
>> }
>>
>>
>>
>> This is the car class:
>>
>> @Root(strict = false, name = "Car")
>>
>> public class Car
>>
>> {
>>
>> @Attribute
>>
>> public double length;
>>
>>
>>
>> @Attribute
>>
>> public String color;
>>
>>
>>
>> @Attribute
>>
>> public int nrOfDoors;
>>
>>
>>
>> @ElementMap(required = false)
>>
>> public HashMap<String,
>> String> furtherAttributes;
>>
>> }
>>
>>
>>
>> And this how I set the converter. Set the converter by
>> AnnotationStategy and @Convert never works.
>>
>> public void testCar() throws
>> Exception
>>
>> {
>>
>> Car car = new
>> Car();
>>
>> car.color =
>> "red";
>>
>> car.length =
>> 4.3;
>>
>> car.nrOfDoors =
>> 4;
>>
>>
>>
>>
>> car.furtherAttributes = new HashMap<String,
>> String>();
>>
>>
>> car.furtherAttributes.put("fuelConsumption",
>> "7.8");
>>
>>
>> car.furtherAttributes.put("fopSpeed",
>> "190");
>>
>>
>>
>> Registry
>> registry = new Registry();
>>
>> RegistryStrategy
>> strategy = new
>> RegistryStrategy(registry);
>>
>>
>>
>>
>> registry.bind(HashMap.class, HashMapConverter.class);
>>
>>
>> //registry.bind(Car.class, CarConverter.class);
>>
>>
>>
>> StringWriter
>> stringwriter = new StringWriter();
>>
>> Serializer
>> serializer = new Persister(strategy);
>>
>>
>> serializer.write(car, stringwriter);
>>
>>
>>
>> String xml =
>> stringwriter.toString();
>>
>> }
>>
>>
>>
>> But on this try, the read method of the converter is
>> never called
>> (There is not furtherAttributes xml element) and I
>> can't set
>> attributes on the parent node. (See comments in the
>> HashMapConverter)
>>
>>
>>
>> The second try was a converter for the car class:
>>
>> public class CarConverter implements
>> Converter<Car>
>>
>> {
>>
>> @Override
>>
>> public Car read(InputNode node)
>> throws Exception
>>
>> {
>>
>> Car car = new
>> Car();
>>
>>
>> car.furtherAttributes = new HashMap<String,
>> String>();
>>
>>
>>
>>
>> ArrayList<String> attributesWithAnnotation = new
>> ArrayList<String>();
>>
>> for (Field field
>> : car.getClass().getFields())
>>
>> {
>>
>>
>> if (field.getAnnotation(Attribute.class)
>> != null)
>>
>>
>> {
>>
>>
>> String name =
>> field.getAnnotation(Attribute.class).name();
>>
>>
>>
>>
>> if (name == null ||
>> name.equals(""))
>>
>>
>> {
>>
>>
>>
>> name = field.getName();
>>
>>
>> }
>>
>>
>>
>>
>>
>> attributesWithAnnotation.add(name);
>>
>>
>> }
>>
>> }
>>
>>
>>
>> for (String
>> entry : node.getAttributes())
>>
>> {
>>
>>
>> if
>> (!attributesWithAnnotation.contains(entry))
>>
>>
>> {
>>
>>
>> String
>> furtherAttributeKey = entry;
>>
>>
>> String
>> furtherAttributeValue =
>> node.getAttribute(entry)
>>
>>
>>
>> .getValue();
>>
>>
>>
>>
>>
>> car.furtherAttributes.put(furtherAttributeKey,
>>
>>
>>
>> furtherAttributeValue);
>>
>>
>> }
>>
>> }
>>
>>
>>
>> return car;
>>
>> }
>>
>>
>>
>> @Override
>>
>> public void write(OutputNode
>> outputNode, Car car) throws
>> Exception
>>
>> {
>>
>> if
>> (car.furtherAttributes != null &&
>> car.furtherAttributes.size() > 0)
>>
>> {
>>
>>
>> for (Entry<String, String> entry :
>> car.furtherAttributes.entrySet())
>>
>>
>> {
>>
>>
>>
>> outputNode.setAttribute(entry.getKey(),
>> entry.getValue());
>>
>>
>> }
>>
>> }
>>
>> }
>>
>> }
>>
>>
>>
>> But there is the problem that only futherAttributes
>> are serialised
>> and deserialised correctly.
>>
>> In the read method I create the car object myself. So
>> color,
>> length and the other field have the default value.
>>
>> But I want, that all that fields are filled by
>> SimpleXml.
>>
>>
>>
>> What converter do you recommend?
>>
>>
>>
>>
>>
>> Am 15.11.2012 23:45, schrieb Niall Gallagher -
>> Yieldbroker:
>>
>>
>>
>> Sorry, my mistake I should have suggested a
>> converter. Here you can use @Convert annotation like so.
>>
>> @Convert(CarConverter.class)
>> Map<String, String> var;
>>
>> Take a look at the following converters
>>
>> https://simple.svn.sf.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/HideEnclosingConverterTest.java
>> https://simple.svn.sf.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/ExampleConverters.java
>>
>>
>> -----Original Message-----
>> From: Christian Klotz [mailto:c....@sp...]
>>
>> Sent: Friday, 16 November 2012 12:28 AM
>> To: Niall Gallagher - Yieldbroker
>> Cc: sim...@li...
>> Subject: Re: [Simple-support] Serialize and deserialize
>> undefined Xml attributes into a HashMap<String,
>> String>
>>
>> Hi Niall,
>>
>> thanks for your quick response.
>>
>>
>> Now I have implemented an Visitor.
>> In the read method, I can get a nodeMap with all xml
>> attributes.
>>
>> I can also detect via refection which attributes have the
>> annotation @Attribute.
>> All other attributes should be stored in the HashMap
>> "furtherAttributes".
>>
>> But I don't known how to put them into the HashMap
>> "furtherAttributes".
>> I do not have the resulting car object. Do you have any tip?
>>
>> public class AnyAttributesVisitor implements Visitor {
>> @Override
>> public void read(Type type, NodeMap<InputNode>
>> nodeMap) throws Exception
>> {
>> // nodeMap contains all xml attributes of the car
>> xml
>> // Content is:
>> // {color=attribute color='red',
>> length=attribute length='4.3',
>> // nrOfDoors=attribute nrOfDoors='4',
>> fuelConsumption=attribute
>> // fuelConsumption='7.8',
>> topSpeed=attribute topSpeed='190'}
>>
>>
>> //Detect attributes with Annotation @Attribute
>> ArrayList<String> attributesWithAnnotation =
>> new
>> ArrayList<String>();
>> for (Field field : type.getType().getFields())
>> {
>> if (field.getAnnotation(Attribute.class) !=
>> null)
>> {
>> String name =
>> field.getAnnotation(Attribute.class).name();
>>
>> if (name == null ||
>> name.equals(""))
>> {
>> name = field.getName();
>> }
>>
>> attributesWithAnnotation.add(name);
>> }
>> }
>>
>> for (String entry :
>> nodeMap.getNode().getAttributes())
>> {
>> if (!attributesWithAnnotation.contains(entry))
>> {
>> String furtherAttributeKey = entry;
>> String furtherAttributeValue =
>> nodeMap.getNode()
>> .getAttribute(entry).getValue();
>>
>> // TODO: Add Key and Value to the Hashmap
>> furtherAttributes
>>
>> nodeMap.remove(furtherAttributeKey);
>> }
>> }
>> }
>>
>> @Override
>> public void write(Type type, NodeMap<OutputNode>
>> nodeMap) throws
>> Exception
>> {
>>
>> }
>> }
>>
>> This is my test case:
>> public void testCarDeserialisation() throws Exception
>> {
>> String xml = "<Car
>> color=\"red\"
>> length=\"4.3\"
>> nrOfDoors=\"4\"
>> fuelConsumption=\"7.8\"
>> topSpeed=\"190\" />";
>>
>> Serializer serializer = new Persister(new
>> VisitorStrategy(
>> new AnyAttributesVisitor()));
>>
>> Car car = serializer.read(Car.class, xml);
>> }
>>
>> Thanks Christian
>>
>> Am 15.11.2012 00:33, schrieb Niall Gallagher - Yieldbroker:
>>
>>
>> I think a Visitor would be simpler than a
>> Strategy, there are many test cases doing this very thing.
>> Just browse through them, I am sure you will find a
>> template. You can browse them here http://simple.svn.sourceforge.net/viewvc/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/
>>
>> -----Original Message-----
>> From: Christian Klotz [mailto:c....@sp...]
>> Sent: Wednesday, 14 November 2012 8:26 PM
>> To: sim...@li...
>> Subject: [Simple-support] Serialize and deserialize
>> undefined Xml attributes into a HashMap<String,
>> String>
>>
>> Hi SimpleXml Team,
>>
>> I use SimpleXml frequently on android and it is great.
>>
>> Now I have a question how to do that job:
>> All XML attributes that are not defined in the Java class
>> with @Attribute should be serialized and deserialized into a
>> HashMap<String,String>.
>>
>> Here is an example:
>>
>> This is out test class "Car"
>>
>> @Root(strict = false, name = "Car")
>> public class Car
>> {
>> @Attribute
>> public double length;
>>
>> @Attribute
>> public String color;
>>
>> @Attribute
>> public int nrOfDoors;
>>
>> public HashMap<String, String> furtherAttributes
>> = new HashMap<String, String>(); }
>>
>> And this is the serialization test method:
>> public void testCar() throws Exception
>> {
>> Car car = new Car();
>>
>> car.color = "red";
>> car.length = 4.3;
>> car.nrOfDoors = 4;
>>
>>
>> car.furtherAttributes.put("fuelConsumption",
>> "7.8");
>> car.furtherAttributes.put("topSpeed",
>> "190");
>>
>> Serializer serializer = new Persister();
>> StringWriter stringwriter = new StringWriter();
>> serializer.write(car, stringwriter);
>>
>> String xml = stringwriter.toString();
>> }
>>
>>
>> The result of the serialization is:
>> <Car color="red" length="4.3"
>> nrOfDoors="4"/>
>>
>> So the furtherAttributes of the HashMap are missing. The
>> result should be:
>> <Car color="red" length="4.3"
>> nrOfDoors="4" fuelConsumption="7.8"
>> topSpeed="190" />
>>
>> And the way back should also work:
>> So if we have a xml like this:
>> <Car color="green" length="3.3"
>> nrOfDoors="2" topSpeed="190"
>> brand="audi" /> After the deserialization the
>> HashMap "furtherAttributes" should have the two
>> undefined attributes "topSpeed" and
>> "brand".
>>
>> I already read the mailing list and some SimpleXml test
>> cases.
>> So I try implement a new Strategy to solve that problem.
>>
>> The AnyAttributeRegistryStrategy looks for classes with
>> annotation "AnyClass" and inside that class
>> searches for the annotation "Any".
>> The annotation "Any" is used to tag the HashMap,
>> where the futher attributes should be serialized to.
>>
>> public class AnyAttributeRegistryStrategy extends
>> RegistryStrategy {
>> public AnyAttributeRegistryStrategy(Registry registry)
>> {
>> super(registry);
>> }
>>
>> @Override
>> public boolean write(Type type, Object value,
>> NodeMap<OutputNode> node,
>> @SuppressWarnings("rawtypes") Map
>> map) throws Exception
>> {
>>
>> if (value.getClass().getAnnotation(AnyClass.class)
>> != null)
>> {
>> for (Field field :
>> value.getClass().getFields())
>> {
>> if (field.getAnnotation(Any.class) !=
>> null)
>> {
>> Object mapObject = field.get(value);
>> if (mapObject instanceof Map<?,
>> ?>)
>> {
>> Map<?, ?> keyValueMap =
>> (Map<?, ?>) mapObject;
>> for (Entry<?, ?>
>> keyValuePair :
>> keyValueMap.entrySet())
>> {
>> if (keyValuePair.getKey() !=
>> null
>> &&
>> keyValuePair.getValue() != null)
>> {
>>
>> node.getNode().setAttribute(
>> keyValuePair.getKey().toString(),
>> keyValuePair.getValue().toString());
>> }
>> }
>>
>> }
>> }
>> }
>> }
>>
>> return super.write(type, value, node, map);
>> }
>> }
>>
>> And this is the Car class with the new annotations:
>> @AnyClass
>> @Root(strict = false, name = "Car")
>> public class Car
>> {
>> @Attribute
>> public double length;
>>
>> @Attribute
>> public String color;
>>
>> @Attribute
>> public int nrOfDoors;
>>
>> @Any
>> public HashMap<String, String> furtherAttributes
>> = new HashMap<String, String>(); }
>>
>> Now the serialisation of the class to xml works.
>> But I do not have a correctly working solution for the
>> deserialisation.
>> Do you have any ideas?
>>
>> Thanks for you help
>>
>> Christian Klotz
>>
>>
>>
>>
>>
>>
>> ------------------------------------------------------------------------------
>> Monitor your physical, virtual and cloud infrastructure from
>> a single web console. Get in-depth insight into apps,
>> servers, databases, vmware, SAP, cloud infrastructure, etc.
>> Download 30-day Free Trial.
>> Pricing starts from $795 for 25 servers or applications!
>> http://p.sf.net/sfu/zoho_dev2dev_nov
>> _______________________________________________
>> Simple-support mailing list
>> Sim...@li...
>> https://lists.sourceforge.net/lists/listinfo/simple-support
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>> --
>> Mit freundlichen Grüßen / Kind regards
>>
>> Christian Klotz
>> Software Engineer
>>
>>
>> SPEDION GmbH
>> Industriestraße 7
>> D - 63829 Krombach
>> Fon: +49 (0) 6024 / 50990-132
>> Fax: +49 (0) 6024 / 50990-121
>> mailto:c....@sp...
>>
>> SPEDION GmbH - Industriestraße 7 - 63829 Krombach -
>> Germany
>> Amtsgericht Aschaffenburg, HRB 8647
>> Geschäftsführer: Günter Englert, Wolfram
>> Grohse
>>
>>
>>
>>
>> -----Inline Attachment Follows-----
>>
>> ------------------------------------------------------------------------------
>> Monitor your physical, virtual and cloud infrastructure from
>> a single
>> web console. Get in-depth insight into apps, servers,
>> databases, vmware,
>> SAP, cloud infrastructure, etc. Download 30-day Free Trial.
>> Pricing starts from $795 for 25 servers or applications!
>> http://p.sf.net/sfu/zoho_dev2dev_nov
>> -----Inline Attachment Follows-----
>>
>> _______________________________________________
>> Simple-support mailing list
>> Sim...@li...
>> https://lists.sourceforge.net/lists/listinfo/simple-support
>>
--
Mit freundlichen Grüßen / Kind regards
Christian Klotz
Software Engineer
SPEDION GmbH
Industriestraße 7
D - 63829 Krombach
Fon: +49 (0) 6024 / 50990-132
Fax: +49 (0) 6024 / 50990-121
mailto:c....@sp...
SPEDION GmbH - Industriestraße 7 - 63829 Krombach - Germany
Amtsgericht Aschaffenburg, HRB 8647
Geschäftsführer: Günter Englert, Wolfram Grohse
|
|
From: stephen t. <ste...@gm...> - 2012-11-19 09:22:23
|
Hi, I'm having some difficulty deserializing some xml on Android - (it's about 100KB) and I've found that whilst occasionally it deserializes in a second or so - it very often takes 15-20 seconds. I was wondering if anyone else has seen this issue (I'm using the 2.6.7). I was trying digging around - and as far as I can see on Android internally it only uses DOM? Is this correct? Should I be also adding the STax jars to my project? Thanks Stephen |
|
From: Niall G. <gal...@ya...> - 2012-11-17 03:03:38
|
You are doing far too much work here, let the framework handle most of it. I normally would not do this, but since there is no good example in the test cases I have implemented it and added it here. I does your Car schema. https://niallg@simple.svn.sourceforge.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/DynamicMapOfAttributesTest.java --- On Fri, 16/11/12, Christian Klotz <c....@sp...> wrote: > From: Christian Klotz <c....@sp...> > Subject: Re: [Simple-support] Serialize and deserialize undefined Xml attributes into a HashMap<String, String> > To: "Niall Gallagher - Yieldbroker" <Nia...@yi...> > Cc: "sim...@li..." <sim...@li...> > Received: Friday, 16 November, 2012, 9:41 AM > > > > > > > Ah ok, thanks. > > > > Now I tried it with two converters. > > > > The first one is this: > > public class HashMapConverter implements > Converter<HashMap<String, String>> > > { > > @Override > > public HashMap<String, > String> read(InputNode node) > throws Exception > > { > > // Is never > called > > return null; > > } > > > > @Override > > public void write(OutputNode node, > HashMap<String, > String> hashMap) > > > throws Exception > > { > > OutputNode > parent = node.getParent(); > > > > for > (Entry<String, String> entry : > hashMap.entrySet()) > > { > > > //Does not work > > > parent.setAttribute(entry.getKey(), > entry.getValue()); > > } > > > > node.remove(); > > } > > } > > > > This is the car class: > > @Root(strict = false, name = "Car") > > public class Car > > { > > @Attribute > > public double length; > > > > @Attribute > > public String color; > > > > @Attribute > > public int nrOfDoors; > > > > @ElementMap(required = false) > > public HashMap<String, > String> furtherAttributes; > > } > > > > And this how I set the converter. Set the converter by > AnnotationStategy and @Convert never works. > > public void testCar() throws > Exception > > { > > Car car = new > Car(); > > car.color = > "red"; > > car.length = > 4.3; > > car.nrOfDoors = > 4; > > > > > car.furtherAttributes = new HashMap<String, > String>(); > > > car.furtherAttributes.put("fuelConsumption", > "7.8"); > > > car.furtherAttributes.put("fopSpeed", > "190"); > > > > Registry > registry = new Registry(); > > RegistryStrategy > strategy = new > RegistryStrategy(registry); > > > > > registry.bind(HashMap.class, HashMapConverter.class); > > > //registry.bind(Car.class, CarConverter.class); > > > > StringWriter > stringwriter = new StringWriter(); > > Serializer > serializer = new Persister(strategy); > > > serializer.write(car, stringwriter); > > > > String xml = > stringwriter.toString(); > > } > > > > But on this try, the read method of the converter is > never called > (There is not furtherAttributes xml element) and I > can't set > attributes on the parent node. (See comments in the > HashMapConverter) > > > > The second try was a converter for the car class: > > public class CarConverter implements > Converter<Car> > > { > > @Override > > public Car read(InputNode node) > throws Exception > > { > > Car car = new > Car(); > > > car.furtherAttributes = new HashMap<String, > String>(); > > > > > ArrayList<String> attributesWithAnnotation = new > ArrayList<String>(); > > for (Field field > : car.getClass().getFields()) > > { > > > if (field.getAnnotation(Attribute.class) > != null) > > > { > > > String name = > field.getAnnotation(Attribute.class).name(); > > > > > if (name == null || > name.equals("")) > > > { > > > > name = field.getName(); > > > } > > > > > > attributesWithAnnotation.add(name); > > > } > > } > > > > for (String > entry : node.getAttributes()) > > { > > > if > (!attributesWithAnnotation.contains(entry)) > > > { > > > String > furtherAttributeKey = entry; > > > String > furtherAttributeValue = > node.getAttribute(entry) > > > > .getValue(); > > > > > > car.furtherAttributes.put(furtherAttributeKey, > > > > furtherAttributeValue); > > > } > > } > > > > return car; > > } > > > > @Override > > public void write(OutputNode > outputNode, Car car) throws > Exception > > { > > if > (car.furtherAttributes != null && > car.furtherAttributes.size() > 0) > > { > > > for (Entry<String, String> entry : > car.furtherAttributes.entrySet()) > > > { > > > > outputNode.setAttribute(entry.getKey(), > entry.getValue()); > > > } > > } > > } > > } > > > > But there is the problem that only futherAttributes > are serialised > and deserialised correctly. > > In the read method I create the car object myself. So > color, > length and the other field have the default value. > > But I want, that all that fields are filled by > SimpleXml. > > > > What converter do you recommend? > > > > > > Am 15.11.2012 23:45, schrieb Niall Gallagher - > Yieldbroker: > > > > Sorry, my mistake I should have suggested a > converter. Here you can use @Convert annotation like so. > > @Convert(CarConverter.class) > Map<String, String> var; > > Take a look at the following converters > > https://simple.svn.sf.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/HideEnclosingConverterTest.java > https://simple.svn.sf.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/ExampleConverters.java > > > -----Original Message----- > From: Christian Klotz [mailto:c....@sp...] > > Sent: Friday, 16 November 2012 12:28 AM > To: Niall Gallagher - Yieldbroker > Cc: sim...@li... > Subject: Re: [Simple-support] Serialize and deserialize > undefined Xml attributes into a HashMap<String, > String> > > Hi Niall, > > thanks for your quick response. > > > Now I have implemented an Visitor. > In the read method, I can get a nodeMap with all xml > attributes. > > I can also detect via refection which attributes have the > annotation @Attribute. > All other attributes should be stored in the HashMap > "furtherAttributes". > > But I don't known how to put them into the HashMap > "furtherAttributes". > I do not have the resulting car object. Do you have any tip? > > public class AnyAttributesVisitor implements Visitor { > @Override > public void read(Type type, NodeMap<InputNode> > nodeMap) throws Exception > { > // nodeMap contains all xml attributes of the car > xml > // Content is: > // {color=attribute color='red', > length=attribute length='4.3', > // nrOfDoors=attribute nrOfDoors='4', > fuelConsumption=attribute > // fuelConsumption='7.8', > topSpeed=attribute topSpeed='190'} > > > //Detect attributes with Annotation @Attribute > ArrayList<String> attributesWithAnnotation = > new > ArrayList<String>(); > for (Field field : type.getType().getFields()) > { > if (field.getAnnotation(Attribute.class) != > null) > { > String name = > field.getAnnotation(Attribute.class).name(); > > if (name == null || > name.equals("")) > { > name = field.getName(); > } > > attributesWithAnnotation.add(name); > } > } > > for (String entry : > nodeMap.getNode().getAttributes()) > { > if (!attributesWithAnnotation.contains(entry)) > { > String furtherAttributeKey = entry; > String furtherAttributeValue = > nodeMap.getNode() > .getAttribute(entry).getValue(); > > // TODO: Add Key and Value to the Hashmap > furtherAttributes > > nodeMap.remove(furtherAttributeKey); > } > } > } > > @Override > public void write(Type type, NodeMap<OutputNode> > nodeMap) throws > Exception > { > > } > } > > This is my test case: > public void testCarDeserialisation() throws Exception > { > String xml = "<Car > color=\"red\" > length=\"4.3\" > nrOfDoors=\"4\" > fuelConsumption=\"7.8\" > topSpeed=\"190\" />"; > > Serializer serializer = new Persister(new > VisitorStrategy( > new AnyAttributesVisitor())); > > Car car = serializer.read(Car.class, xml); > } > > Thanks Christian > > Am 15.11.2012 00:33, schrieb Niall Gallagher - Yieldbroker: > > > I think a Visitor would be simpler than a > Strategy, there are many test cases doing this very thing. > Just browse through them, I am sure you will find a > template. You can browse them here http://simple.svn.sourceforge.net/viewvc/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/ > > -----Original Message----- > From: Christian Klotz [mailto:c....@sp...] > Sent: Wednesday, 14 November 2012 8:26 PM > To: sim...@li... > Subject: [Simple-support] Serialize and deserialize > undefined Xml attributes into a HashMap<String, > String> > > Hi SimpleXml Team, > > I use SimpleXml frequently on android and it is great. > > Now I have a question how to do that job: > All XML attributes that are not defined in the Java class > with @Attribute should be serialized and deserialized into a > HashMap<String,String>. > > Here is an example: > > This is out test class "Car" > > @Root(strict = false, name = "Car") > public class Car > { > @Attribute > public double length; > > @Attribute > public String color; > > @Attribute > public int nrOfDoors; > > public HashMap<String, String> furtherAttributes > = new HashMap<String, String>(); } > > And this is the serialization test method: > public void testCar() throws Exception > { > Car car = new Car(); > > car.color = "red"; > car.length = 4.3; > car.nrOfDoors = 4; > > > car.furtherAttributes.put("fuelConsumption", > "7.8"); > car.furtherAttributes.put("topSpeed", > "190"); > > Serializer serializer = new Persister(); > StringWriter stringwriter = new StringWriter(); > serializer.write(car, stringwriter); > > String xml = stringwriter.toString(); > } > > > The result of the serialization is: > <Car color="red" length="4.3" > nrOfDoors="4"/> > > So the furtherAttributes of the HashMap are missing. The > result should be: > <Car color="red" length="4.3" > nrOfDoors="4" fuelConsumption="7.8" > topSpeed="190" /> > > And the way back should also work: > So if we have a xml like this: > <Car color="green" length="3.3" > nrOfDoors="2" topSpeed="190" > brand="audi" /> After the deserialization the > HashMap "furtherAttributes" should have the two > undefined attributes "topSpeed" and > "brand". > > I already read the mailing list and some SimpleXml test > cases. > So I try implement a new Strategy to solve that problem. > > The AnyAttributeRegistryStrategy looks for classes with > annotation "AnyClass" and inside that class > searches for the annotation "Any". > The annotation "Any" is used to tag the HashMap, > where the futher attributes should be serialized to. > > public class AnyAttributeRegistryStrategy extends > RegistryStrategy { > public AnyAttributeRegistryStrategy(Registry registry) > { > super(registry); > } > > @Override > public boolean write(Type type, Object value, > NodeMap<OutputNode> node, > @SuppressWarnings("rawtypes") Map > map) throws Exception > { > > if (value.getClass().getAnnotation(AnyClass.class) > != null) > { > for (Field field : > value.getClass().getFields()) > { > if (field.getAnnotation(Any.class) != > null) > { > Object mapObject = field.get(value); > if (mapObject instanceof Map<?, > ?>) > { > Map<?, ?> keyValueMap = > (Map<?, ?>) mapObject; > for (Entry<?, ?> > keyValuePair : > keyValueMap.entrySet()) > { > if (keyValuePair.getKey() != > null > && > keyValuePair.getValue() != null) > { > > node.getNode().setAttribute( > keyValuePair.getKey().toString(), > keyValuePair.getValue().toString()); > } > } > > } > } > } > } > > return super.write(type, value, node, map); > } > } > > And this is the Car class with the new annotations: > @AnyClass > @Root(strict = false, name = "Car") > public class Car > { > @Attribute > public double length; > > @Attribute > public String color; > > @Attribute > public int nrOfDoors; > > @Any > public HashMap<String, String> furtherAttributes > = new HashMap<String, String>(); } > > Now the serialisation of the class to xml works. > But I do not have a correctly working solution for the > deserialisation. > Do you have any ideas? > > Thanks for you help > > Christian Klotz > > > > > > > ------------------------------------------------------------------------------ > Monitor your physical, virtual and cloud infrastructure from > a single web console. Get in-depth insight into apps, > servers, databases, vmware, SAP, cloud infrastructure, etc. > Download 30-day Free Trial. > Pricing starts from $795 for 25 servers or applications! > http://p.sf.net/sfu/zoho_dev2dev_nov > _______________________________________________ > Simple-support mailing list > Sim...@li... > https://lists.sourceforge.net/lists/listinfo/simple-support > > > > > > > > > > > > -- > Mit freundlichen Grüßen / Kind regards > > Christian Klotz > Software Engineer > > > SPEDION GmbH > Industriestraße 7 > D - 63829 Krombach > Fon: +49 (0) 6024 / 50990-132 > Fax: +49 (0) 6024 / 50990-121 > mailto:c....@sp... > > SPEDION GmbH - Industriestraße 7 - 63829 Krombach - > Germany > Amtsgericht Aschaffenburg, HRB 8647 > Geschäftsführer: Günter Englert, Wolfram > Grohse > > > > > -----Inline Attachment Follows----- > > ------------------------------------------------------------------------------ > Monitor your physical, virtual and cloud infrastructure from > a single > web console. Get in-depth insight into apps, servers, > databases, vmware, > SAP, cloud infrastructure, etc. Download 30-day Free Trial. > Pricing starts from $795 for 25 servers or applications! > http://p.sf.net/sfu/zoho_dev2dev_nov > -----Inline Attachment Follows----- > > _______________________________________________ > Simple-support mailing list > Sim...@li... > https://lists.sourceforge.net/lists/listinfo/simple-support > |
|
From: Christian K. <c....@sp...> - 2012-11-16 17:41:48
|
Ah ok, thanks.
Now I tried it with two converters.
*The first one is this:*
public class HashMapConverter implements Converter<HashMap<String, String>>
{
@Override
public HashMap<String, String> read(InputNode node) throws Exception
{
// Is never called
return null;
}
@Override
public void write(OutputNode node, HashMap<String, String> hashMap)
throws Exception
{
OutputNode parent = node.getParent();
for (Entry<String, String> entry : hashMap.entrySet())
{
//Does not work
parent.setAttribute(entry.getKey(), entry.getValue());
}
node.remove();
}
}
This is the car class:
@Root(strict = false, name = "Car")
public class Car
{
@Attribute
public double length;
@Attribute
public String color;
@Attribute
public int nrOfDoors;
@ElementMap(required = false)
public HashMap<String, String> furtherAttributes;
}
And this how I set the converter. Set the converter by AnnotationStategy
and @Convert never works.
public void testCar() throws Exception
{
Car car = new Car();
car.color = "red";
car.length = 4.3;
car.nrOfDoors = 4;
car.furtherAttributes = new HashMap<String, String>();
car.furtherAttributes.put("fuelConsumption", "7.8");
car.furtherAttributes.put("fopSpeed", "190");
Registry registry = new Registry();
RegistryStrategy strategy = new RegistryStrategy(registry);
registry.bind(HashMap.class, HashMapConverter.class);
//registry.bind(Car.class, CarConverter.class);
StringWriter stringwriter = new StringWriter();
Serializer serializer = new Persister(strategy);
serializer.write(car, stringwriter);
String xml = stringwriter.toString();
}
But on this try, the read method of the converter is never called (There
is not furtherAttributes xml element) and I can't set attributes on the
parent node. (See comments in the HashMapConverter)
The second try was a converter for the car class:
public class CarConverter implements Converter<Car>
{
@Override
public Car read(InputNode node) throws Exception
{
Car car = new Car();
car.furtherAttributes = new HashMap<String, String>();
ArrayList<String> attributesWithAnnotation = new
ArrayList<String>();
for (Field field : car.getClass().getFields())
{
if (field.getAnnotation(Attribute.class) != null)
{
String name = field.getAnnotation(Attribute.class).name();
if (name == null || name.equals(""))
{
name = field.getName();
}
attributesWithAnnotation.add(name);
}
}
for (String entry : node.getAttributes())
{
if (!attributesWithAnnotation.contains(entry))
{
String furtherAttributeKey = entry;
String furtherAttributeValue = node.getAttribute(entry)
.getValue();
car.furtherAttributes.put(furtherAttributeKey,
furtherAttributeValue);
}
}
return car;
}
@Override
public void write(OutputNode outputNode, Car car) throws Exception
{
if (car.furtherAttributes != null &&
car.furtherAttributes.size() > 0)
{
for (Entry<String, String> entry :
car.furtherAttributes.entrySet())
{
outputNode.setAttribute(entry.getKey(), entry.getValue());
}
}
}
}
But there is the problem that only futherAttributes are serialised and
deserialised correctly.
In the read method I create the car object myself. So color, length and
the other field have the default value.
But I want, that all that fields are filled by SimpleXml.
What converter do you recommend?
Am 15.11.2012 23:45, schrieb Niall Gallagher - Yieldbroker:
> Sorry, my mistake I should have suggested a converter. Here you can use @Convert annotation like so.
>
> @Convert(CarConverter.class)
> Map<String, String> var;
>
> Take a look at the following converters
>
> https://simple.svn.sf.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/HideEnclosingConverterTest.java
> https://simple.svn.sf.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/ExampleConverters.java
>
>
> -----Original Message-----
> From: Christian Klotz [mailto:c....@sp...]
> Sent: Friday, 16 November 2012 12:28 AM
> To: Niall Gallagher - Yieldbroker
> Cc: sim...@li...
> Subject: Re: [Simple-support] Serialize and deserialize undefined Xml attributes into a HashMap<String, String>
>
> Hi Niall,
>
> thanks for your quick response.
>
>
> Now I have implemented an Visitor.
> In the read method, I can get a nodeMap with all xml attributes.
>
> I can also detect via refection which attributes have the annotation @Attribute.
> All other attributes should be stored in the HashMap "furtherAttributes".
>
> But I don't known how to put them into the HashMap "furtherAttributes".
> I do not have the resulting car object. Do you have any tip?
>
> public class AnyAttributesVisitor implements Visitor {
> @Override
> public void read(Type type, NodeMap<InputNode> nodeMap) throws Exception
> {
> // nodeMap contains all xml attributes of the car xml
> // Content is:
> // {color=attribute color='red', length=attribute length='4.3',
> // nrOfDoors=attribute nrOfDoors='4', fuelConsumption=attribute
> // fuelConsumption='7.8', topSpeed=attribute topSpeed='190'}
>
>
> //Detect attributes with Annotation @Attribute
> ArrayList<String> attributesWithAnnotation = new
> ArrayList<String>();
> for (Field field : type.getType().getFields())
> {
> if (field.getAnnotation(Attribute.class) != null)
> {
> String name = field.getAnnotation(Attribute.class).name();
>
> if (name == null || name.equals(""))
> {
> name = field.getName();
> }
>
> attributesWithAnnotation.add(name);
> }
> }
>
> for (String entry : nodeMap.getNode().getAttributes())
> {
> if (!attributesWithAnnotation.contains(entry))
> {
> String furtherAttributeKey = entry;
> String furtherAttributeValue = nodeMap.getNode()
> .getAttribute(entry).getValue();
>
> // TODO: Add Key and Value to the Hashmap furtherAttributes
>
> nodeMap.remove(furtherAttributeKey);
> }
> }
> }
>
> @Override
> public void write(Type type, NodeMap<OutputNode> nodeMap) throws
> Exception
> {
>
> }
> }
>
> This is my test case:
> public void testCarDeserialisation() throws Exception
> {
> String xml = "<Car color=\"red\" length=\"4.3\" nrOfDoors=\"4\"
> fuelConsumption=\"7.8\" topSpeed=\"190\" />";
>
> Serializer serializer = new Persister(new VisitorStrategy(
> new AnyAttributesVisitor()));
>
> Car car = serializer.read(Car.class, xml);
> }
>
> Thanks Christian
>
> Am 15.11.2012 00:33, schrieb Niall Gallagher - Yieldbroker:
>> I think a Visitor would be simpler than a Strategy, there are many test cases doing this very thing. Just browse through them, I am sure you will find a template. You can browse them here http://simple.svn.sourceforge.net/viewvc/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/
>>
>> -----Original Message-----
>> From: Christian Klotz [mailto:c....@sp...]
>> Sent: Wednesday, 14 November 2012 8:26 PM
>> To: sim...@li...
>> Subject: [Simple-support] Serialize and deserialize undefined Xml attributes into a HashMap<String, String>
>>
>> Hi SimpleXml Team,
>>
>> I use SimpleXml frequently on android and it is great.
>>
>> Now I have a question how to do that job:
>> All XML attributes that are not defined in the Java class with @Attribute should be serialized and deserialized into a HashMap<String,String>.
>>
>> Here is an example:
>>
>> This is out test class "Car"
>>
>> @Root(strict = false, name = "Car")
>> public class Car
>> {
>> @Attribute
>> public double length;
>>
>> @Attribute
>> public String color;
>>
>> @Attribute
>> public int nrOfDoors;
>>
>> public HashMap<String, String> furtherAttributes = new HashMap<String, String>(); }
>>
>> And this is the serialization test method:
>> public void testCar() throws Exception
>> {
>> Car car = new Car();
>>
>> car.color = "red";
>> car.length = 4.3;
>> car.nrOfDoors = 4;
>>
>> car.furtherAttributes.put("fuelConsumption", "7.8");
>> car.furtherAttributes.put("topSpeed", "190");
>>
>> Serializer serializer = new Persister();
>> StringWriter stringwriter = new StringWriter();
>> serializer.write(car, stringwriter);
>>
>> String xml = stringwriter.toString();
>> }
>>
>>
>> The result of the serialization is:
>> <Car color="red" length="4.3" nrOfDoors="4"/>
>>
>> So the furtherAttributes of the HashMap are missing. The result should be:
>> <Car color="red" length="4.3" nrOfDoors="4" fuelConsumption="7.8"
>> topSpeed="190" />
>>
>> And the way back should also work:
>> So if we have a xml like this:
>> <Car color="green" length="3.3" nrOfDoors="2" topSpeed="190" brand="audi" /> After the deserialization the HashMap "furtherAttributes" should have the two undefined attributes "topSpeed" and "brand".
>>
>> I already read the mailing list and some SimpleXml test cases.
>> So I try implement a new Strategy to solve that problem.
>>
>> The AnyAttributeRegistryStrategy looks for classes with annotation "AnyClass" and inside that class searches for the annotation "Any".
>> The annotation "Any" is used to tag the HashMap, where the futher attributes should be serialized to.
>>
>> public class AnyAttributeRegistryStrategy extends RegistryStrategy {
>> public AnyAttributeRegistryStrategy(Registry registry)
>> {
>> super(registry);
>> }
>>
>> @Override
>> public boolean write(Type type, Object value, NodeMap<OutputNode> node,
>> @SuppressWarnings("rawtypes") Map map) throws Exception
>> {
>>
>> if (value.getClass().getAnnotation(AnyClass.class) != null)
>> {
>> for (Field field : value.getClass().getFields())
>> {
>> if (field.getAnnotation(Any.class) != null)
>> {
>> Object mapObject = field.get(value);
>> if (mapObject instanceof Map<?, ?>)
>> {
>> Map<?, ?> keyValueMap = (Map<?, ?>) mapObject;
>> for (Entry<?, ?> keyValuePair :
>> keyValueMap.entrySet())
>> {
>> if (keyValuePair.getKey() != null
>> && keyValuePair.getValue() != null)
>> {
>> node.getNode().setAttribute( keyValuePair.getKey().toString(), keyValuePair.getValue().toString());
>> }
>> }
>>
>> }
>> }
>> }
>> }
>>
>> return super.write(type, value, node, map);
>> }
>> }
>>
>> And this is the Car class with the new annotations:
>> @AnyClass
>> @Root(strict = false, name = "Car")
>> public class Car
>> {
>> @Attribute
>> public double length;
>>
>> @Attribute
>> public String color;
>>
>> @Attribute
>> public int nrOfDoors;
>>
>> @Any
>> public HashMap<String, String> furtherAttributes = new HashMap<String, String>(); }
>>
>> Now the serialisation of the class to xml works.
>> But I do not have a correctly working solution for the deserialisation.
>> Do you have any ideas?
>>
>> Thanks for you help
>>
>> Christian Klotz
>>
>>
>>
>>
>>
>>
>> ------------------------------------------------------------------------------
>> Monitor your physical, virtual and cloud infrastructure from a single web console. Get in-depth insight into apps, servers, databases, vmware, SAP, cloud infrastructure, etc. Download 30-day Free Trial.
>> Pricing starts from $795 for 25 servers or applications!
>> http://p.sf.net/sfu/zoho_dev2dev_nov
>> _______________________________________________
>> Simple-support mailing list
>> Sim...@li...
>> https://lists.sourceforge.net/lists/listinfo/simple-support
>>
>
--
Mit freundlichen Grüßen / Kind regards
Christian Klotz
Software Engineer
SPEDION GmbH
Industriestraße 7
D - 63829 Krombach
Fon: +49 (0) 6024 / 50990-132
Fax: +49 (0) 6024 / 50990-121
mailto:c....@sp...
SPEDION GmbH - Industriestraße 7 - 63829 Krombach - Germany
Amtsgericht Aschaffenburg, HRB 8647
Geschäftsführer: Günter Englert, Wolfram Grohse
|
|
From: Niall G. - Y. <Nia...@yi...> - 2012-11-15 22:45:11
|
Sorry, my mistake I should have suggested a converter. Here you can use @Convert annotation like so. @Convert(CarConverter.class) Map<String, String> var; Take a look at the following converters https://simple.svn.sf.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/HideEnclosingConverterTest.java https://simple.svn.sf.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/convert/ExampleConverters.java -----Original Message----- From: Christian Klotz [mailto:c....@sp...] Sent: Friday, 16 November 2012 12:28 AM To: Niall Gallagher - Yieldbroker Cc: sim...@li... Subject: Re: [Simple-support] Serialize and deserialize undefined Xml attributes into a HashMap<String, String> Hi Niall, thanks for your quick response. Now I have implemented an Visitor. In the read method, I can get a nodeMap with all xml attributes. I can also detect via refection which attributes have the annotation @Attribute. All other attributes should be stored in the HashMap "furtherAttributes". But I don't known how to put them into the HashMap "furtherAttributes". I do not have the resulting car object. Do you have any tip? public class AnyAttributesVisitor implements Visitor { @Override public void read(Type type, NodeMap<InputNode> nodeMap) throws Exception { // nodeMap contains all xml attributes of the car xml // Content is: // {color=attribute color='red', length=attribute length='4.3', // nrOfDoors=attribute nrOfDoors='4', fuelConsumption=attribute // fuelConsumption='7.8', topSpeed=attribute topSpeed='190'} //Detect attributes with Annotation @Attribute ArrayList<String> attributesWithAnnotation = new ArrayList<String>(); for (Field field : type.getType().getFields()) { if (field.getAnnotation(Attribute.class) != null) { String name = field.getAnnotation(Attribute.class).name(); if (name == null || name.equals("")) { name = field.getName(); } attributesWithAnnotation.add(name); } } for (String entry : nodeMap.getNode().getAttributes()) { if (!attributesWithAnnotation.contains(entry)) { String furtherAttributeKey = entry; String furtherAttributeValue = nodeMap.getNode() .getAttribute(entry).getValue(); // TODO: Add Key and Value to the Hashmap furtherAttributes nodeMap.remove(furtherAttributeKey); } } } @Override public void write(Type type, NodeMap<OutputNode> nodeMap) throws Exception { } } This is my test case: public void testCarDeserialisation() throws Exception { String xml = "<Car color=\"red\" length=\"4.3\" nrOfDoors=\"4\" fuelConsumption=\"7.8\" topSpeed=\"190\" />"; Serializer serializer = new Persister(new VisitorStrategy( new AnyAttributesVisitor())); Car car = serializer.read(Car.class, xml); } Thanks Christian Am 15.11.2012 00:33, schrieb Niall Gallagher - Yieldbroker: > I think a Visitor would be simpler than a Strategy, there are many test cases doing this very thing. Just browse through them, I am sure you will find a template. You can browse them here http://simple.svn.sourceforge.net/viewvc/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/ > > -----Original Message----- > From: Christian Klotz [mailto:c....@sp...] > Sent: Wednesday, 14 November 2012 8:26 PM > To: sim...@li... > Subject: [Simple-support] Serialize and deserialize undefined Xml attributes into a HashMap<String, String> > > Hi SimpleXml Team, > > I use SimpleXml frequently on android and it is great. > > Now I have a question how to do that job: > All XML attributes that are not defined in the Java class with @Attribute should be serialized and deserialized into a HashMap<String,String>. > > Here is an example: > > This is out test class "Car" > > @Root(strict = false, name = "Car") > public class Car > { > @Attribute > public double length; > > @Attribute > public String color; > > @Attribute > public int nrOfDoors; > > public HashMap<String, String> furtherAttributes = new HashMap<String, String>(); } > > And this is the serialization test method: > public void testCar() throws Exception > { > Car car = new Car(); > > car.color = "red"; > car.length = 4.3; > car.nrOfDoors = 4; > > car.furtherAttributes.put("fuelConsumption", "7.8"); > car.furtherAttributes.put("topSpeed", "190"); > > Serializer serializer = new Persister(); > StringWriter stringwriter = new StringWriter(); > serializer.write(car, stringwriter); > > String xml = stringwriter.toString(); > } > > > The result of the serialization is: > <Car color="red" length="4.3" nrOfDoors="4"/> > > So the furtherAttributes of the HashMap are missing. The result should be: > <Car color="red" length="4.3" nrOfDoors="4" fuelConsumption="7.8" > topSpeed="190" /> > > And the way back should also work: > So if we have a xml like this: > <Car color="green" length="3.3" nrOfDoors="2" topSpeed="190" brand="audi" /> After the deserialization the HashMap "furtherAttributes" should have the two undefined attributes "topSpeed" and "brand". > > I already read the mailing list and some SimpleXml test cases. > So I try implement a new Strategy to solve that problem. > > The AnyAttributeRegistryStrategy looks for classes with annotation "AnyClass" and inside that class searches for the annotation "Any". > The annotation "Any" is used to tag the HashMap, where the futher attributes should be serialized to. > > public class AnyAttributeRegistryStrategy extends RegistryStrategy { > public AnyAttributeRegistryStrategy(Registry registry) > { > super(registry); > } > > @Override > public boolean write(Type type, Object value, NodeMap<OutputNode> node, > @SuppressWarnings("rawtypes") Map map) throws Exception > { > > if (value.getClass().getAnnotation(AnyClass.class) != null) > { > for (Field field : value.getClass().getFields()) > { > if (field.getAnnotation(Any.class) != null) > { > Object mapObject = field.get(value); > if (mapObject instanceof Map<?, ?>) > { > Map<?, ?> keyValueMap = (Map<?, ?>) mapObject; > for (Entry<?, ?> keyValuePair : > keyValueMap.entrySet()) > { > if (keyValuePair.getKey() != null > && keyValuePair.getValue() != null) > { > node.getNode().setAttribute( keyValuePair.getKey().toString(), keyValuePair.getValue().toString()); > } > } > > } > } > } > } > > return super.write(type, value, node, map); > } > } > > And this is the Car class with the new annotations: > @AnyClass > @Root(strict = false, name = "Car") > public class Car > { > @Attribute > public double length; > > @Attribute > public String color; > > @Attribute > public int nrOfDoors; > > @Any > public HashMap<String, String> furtherAttributes = new HashMap<String, String>(); } > > Now the serialisation of the class to xml works. > But I do not have a correctly working solution for the deserialisation. > Do you have any ideas? > > Thanks for you help > > Christian Klotz > > > > > > > ------------------------------------------------------------------------------ > Monitor your physical, virtual and cloud infrastructure from a single web console. Get in-depth insight into apps, servers, databases, vmware, SAP, cloud infrastructure, etc. Download 30-day Free Trial. > Pricing starts from $795 for 25 servers or applications! > http://p.sf.net/sfu/zoho_dev2dev_nov > _______________________________________________ > Simple-support mailing list > Sim...@li... > https://lists.sourceforge.net/lists/listinfo/simple-support > -- Mit freundlichen Grüßen / Kind regards Christian Klotz Software Engineer SPEDION GmbH Industriestraße 7 D - 63829 Krombach Fon: +49 (0) 6024 / 50990-132 Fax: +49 (0) 6024 / 50990-121 mailto:c....@sp... SPEDION GmbH - Industriestraße 7 - 63829 Krombach - Germany Amtsgericht Aschaffenburg, HRB 8647 Geschäftsführer: Günter Englert, Wolfram Grohse |
|
From: Christian K. <c....@sp...> - 2012-11-15 13:28:15
|
Hi Niall,
thanks for your quick response.
Now I have implemented an Visitor.
In the read method, I can get a nodeMap with all xml attributes.
I can also detect via refection which attributes have the annotation
@Attribute.
All other attributes should be stored in the HashMap "furtherAttributes".
But I don't known how to put them into the HashMap "furtherAttributes".
I do not have the resulting car object. Do you have any tip?
public class AnyAttributesVisitor implements Visitor
{
@Override
public void read(Type type, NodeMap<InputNode> nodeMap) throws
Exception
{
// nodeMap contains all xml attributes of the car xml
// Content is:
// {color=attribute color='red', length=attribute length='4.3',
// nrOfDoors=attribute nrOfDoors='4', fuelConsumption=attribute
// fuelConsumption='7.8', topSpeed=attribute topSpeed='190'}
//Detect attributes with Annotation @Attribute
ArrayList<String> attributesWithAnnotation = new
ArrayList<String>();
for (Field field : type.getType().getFields())
{
if (field.getAnnotation(Attribute.class) != null)
{
String name = field.getAnnotation(Attribute.class).name();
if (name == null || name.equals(""))
{
name = field.getName();
}
attributesWithAnnotation.add(name);
}
}
for (String entry : nodeMap.getNode().getAttributes())
{
if (!attributesWithAnnotation.contains(entry))
{
String furtherAttributeKey = entry;
String furtherAttributeValue = nodeMap.getNode()
.getAttribute(entry).getValue();
// TODO: Add Key and Value to the Hashmap furtherAttributes
nodeMap.remove(furtherAttributeKey);
}
}
}
@Override
public void write(Type type, NodeMap<OutputNode> nodeMap) throws
Exception
{
}
}
This is my test case:
public void testCarDeserialisation() throws Exception
{
String xml = "<Car color=\"red\" length=\"4.3\" nrOfDoors=\"4\"
fuelConsumption=\"7.8\" topSpeed=\"190\" />";
Serializer serializer = new Persister(new VisitorStrategy(
new AnyAttributesVisitor()));
Car car = serializer.read(Car.class, xml);
}
Thanks Christian
Am 15.11.2012 00:33, schrieb Niall Gallagher - Yieldbroker:
> I think a Visitor would be simpler than a Strategy, there are many test cases doing this very thing. Just browse through them, I am sure you will find a template. You can browse them here http://simple.svn.sourceforge.net/viewvc/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/
>
> -----Original Message-----
> From: Christian Klotz [mailto:c....@sp...]
> Sent: Wednesday, 14 November 2012 8:26 PM
> To: sim...@li...
> Subject: [Simple-support] Serialize and deserialize undefined Xml attributes into a HashMap<String, String>
>
> Hi SimpleXml Team,
>
> I use SimpleXml frequently on android and it is great.
>
> Now I have a question how to do that job:
> All XML attributes that are not defined in the Java class with @Attribute should be serialized and deserialized into a HashMap<String,String>.
>
> Here is an example:
>
> This is out test class "Car"
>
> @Root(strict = false, name = "Car")
> public class Car
> {
> @Attribute
> public double length;
>
> @Attribute
> public String color;
>
> @Attribute
> public int nrOfDoors;
>
> public HashMap<String, String> furtherAttributes = new HashMap<String, String>(); }
>
> And this is the serialization test method:
> public void testCar() throws Exception
> {
> Car car = new Car();
>
> car.color = "red";
> car.length = 4.3;
> car.nrOfDoors = 4;
>
> car.furtherAttributes.put("fuelConsumption", "7.8");
> car.furtherAttributes.put("topSpeed", "190");
>
> Serializer serializer = new Persister();
> StringWriter stringwriter = new StringWriter();
> serializer.write(car, stringwriter);
>
> String xml = stringwriter.toString();
> }
>
>
> The result of the serialization is:
> <Car color="red" length="4.3" nrOfDoors="4"/>
>
> So the furtherAttributes of the HashMap are missing. The result should be:
> <Car color="red" length="4.3" nrOfDoors="4" fuelConsumption="7.8"
> topSpeed="190" />
>
> And the way back should also work:
> So if we have a xml like this:
> <Car color="green" length="3.3" nrOfDoors="2" topSpeed="190" brand="audi" /> After the deserialization the HashMap "furtherAttributes" should have the two undefined attributes "topSpeed" and "brand".
>
> I already read the mailing list and some SimpleXml test cases.
> So I try implement a new Strategy to solve that problem.
>
> The AnyAttributeRegistryStrategy looks for classes with annotation "AnyClass" and inside that class searches for the annotation "Any".
> The annotation "Any" is used to tag the HashMap, where the futher attributes should be serialized to.
>
> public class AnyAttributeRegistryStrategy extends RegistryStrategy {
> public AnyAttributeRegistryStrategy(Registry registry)
> {
> super(registry);
> }
>
> @Override
> public boolean write(Type type, Object value, NodeMap<OutputNode> node,
> @SuppressWarnings("rawtypes") Map map) throws Exception
> {
>
> if (value.getClass().getAnnotation(AnyClass.class) != null)
> {
> for (Field field : value.getClass().getFields())
> {
> if (field.getAnnotation(Any.class) != null)
> {
> Object mapObject = field.get(value);
> if (mapObject instanceof Map<?, ?>)
> {
> Map<?, ?> keyValueMap = (Map<?, ?>) mapObject;
> for (Entry<?, ?> keyValuePair :
> keyValueMap.entrySet())
> {
> if (keyValuePair.getKey() != null
> && keyValuePair.getValue() != null)
> {
> node.getNode().setAttribute( keyValuePair.getKey().toString(), keyValuePair.getValue().toString());
> }
> }
>
> }
> }
> }
> }
>
> return super.write(type, value, node, map);
> }
> }
>
> And this is the Car class with the new annotations:
> @AnyClass
> @Root(strict = false, name = "Car")
> public class Car
> {
> @Attribute
> public double length;
>
> @Attribute
> public String color;
>
> @Attribute
> public int nrOfDoors;
>
> @Any
> public HashMap<String, String> furtherAttributes = new HashMap<String, String>(); }
>
> Now the serialisation of the class to xml works.
> But I do not have a correctly working solution for the deserialisation.
> Do you have any ideas?
>
> Thanks for you help
>
> Christian Klotz
>
>
>
>
>
>
> ------------------------------------------------------------------------------
> Monitor your physical, virtual and cloud infrastructure from a single web console. Get in-depth insight into apps, servers, databases, vmware, SAP, cloud infrastructure, etc. Download 30-day Free Trial.
> Pricing starts from $795 for 25 servers or applications!
> http://p.sf.net/sfu/zoho_dev2dev_nov
> _______________________________________________
> Simple-support mailing list
> Sim...@li...
> https://lists.sourceforge.net/lists/listinfo/simple-support
>
--
Mit freundlichen Grüßen / Kind regards
Christian Klotz
Software Engineer
SPEDION GmbH
Industriestraße 7
D - 63829 Krombach
Fon: +49 (0) 6024 / 50990-132
Fax: +49 (0) 6024 / 50990-121
mailto:c....@sp...
SPEDION GmbH - Industriestraße 7 - 63829 Krombach - Germany
Amtsgericht Aschaffenburg, HRB 8647
Geschäftsführer: Günter Englert, Wolfram Grohse
|
|
From: Niall G. <gal...@ya...> - 2012-11-15 10:33:34
|
Hi, Yes, I am the only committer however I do accept contributions. I am using it for a large number of projects and will be maintaining it for the foreseeable future. I will be releasing a new version soon, which like the previous couple of releases will be focused on performance, particularly on Android. I suspect performance will also be the focus of the next couple of releases. The only major addition on a roadmap is the @Literal annotation, which will grab XML as text rather than parse it. This is quite tricky to do so it will be a couple of months before its done. Niall --- On Mon, 5/11/12, Hinkle, Cameron <Cam...@ni...> wrote: > From: Hinkle, Cameron <Cam...@ni...> > Subject: [Simple-support] Roadmap > To: "sim...@li..." <sim...@li...> > Received: Monday, 5 November, 2012, 10:22 AM > Hello, > Does anyone know the roadmap for Simple? > We're using it on a rather large project and I just want > to make sure someone will be maintaining for the foreseeable > future. It seems like Niall is the only committer; are you > still actively working on it or at least addressing bugs > that may come up? > Thanks,Cameron > > -----Inline Attachment Follows----- > > ------------------------------------------------------------------------------ > Monitor your physical, virtual and cloud infrastructure from > a single > web console. Get in-depth insight into apps, servers, > databases, vmware, > SAP, cloud infrastructure, etc. Download 30-day Free Trial. > Pricing starts from $795 for 25 servers or applications! > http://p.sf.net/sfu/zoho_dev2dev_nov > -----Inline Attachment Follows----- > > _______________________________________________ > Simple-support mailing list > Sim...@li... > https://lists.sourceforge.net/lists/listinfo/simple-support > |
|
From: Niall G. - Y. <Nia...@yi...> - 2012-11-14 23:49:53
|
I think a Visitor would be simpler than a Strategy, there are many test cases doing this very thing. Just browse through them, I am sure you will find a template. You can browse them here http://simple.svn.sourceforge.net/viewvc/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/ -----Original Message----- From: Christian Klotz [mailto:c....@sp...] Sent: Wednesday, 14 November 2012 8:26 PM To: sim...@li... Subject: [Simple-support] Serialize and deserialize undefined Xml attributes into a HashMap<String, String> Hi SimpleXml Team, I use SimpleXml frequently on android and it is great. Now I have a question how to do that job: All XML attributes that are not defined in the Java class with @Attribute should be serialized and deserialized into a HashMap<String,String>. Here is an example: This is out test class "Car" @Root(strict = false, name = "Car") public class Car { @Attribute public double length; @Attribute public String color; @Attribute public int nrOfDoors; public HashMap<String, String> furtherAttributes = new HashMap<String, String>(); } And this is the serialization test method: public void testCar() throws Exception { Car car = new Car(); car.color = "red"; car.length = 4.3; car.nrOfDoors = 4; car.furtherAttributes.put("fuelConsumption", "7.8"); car.furtherAttributes.put("topSpeed", "190"); Serializer serializer = new Persister(); StringWriter stringwriter = new StringWriter(); serializer.write(car, stringwriter); String xml = stringwriter.toString(); } The result of the serialization is: <Car color="red" length="4.3" nrOfDoors="4"/> So the furtherAttributes of the HashMap are missing. The result should be: <Car color="red" length="4.3" nrOfDoors="4" fuelConsumption="7.8" topSpeed="190" /> And the way back should also work: So if we have a xml like this: <Car color="green" length="3.3" nrOfDoors="2" topSpeed="190" brand="audi" /> After the deserialization the HashMap "furtherAttributes" should have the two undefined attributes "topSpeed" and "brand". I already read the mailing list and some SimpleXml test cases. So I try implement a new Strategy to solve that problem. The AnyAttributeRegistryStrategy looks for classes with annotation "AnyClass" and inside that class searches for the annotation "Any". The annotation "Any" is used to tag the HashMap, where the futher attributes should be serialized to. public class AnyAttributeRegistryStrategy extends RegistryStrategy { public AnyAttributeRegistryStrategy(Registry registry) { super(registry); } @Override public boolean write(Type type, Object value, NodeMap<OutputNode> node, @SuppressWarnings("rawtypes") Map map) throws Exception { if (value.getClass().getAnnotation(AnyClass.class) != null) { for (Field field : value.getClass().getFields()) { if (field.getAnnotation(Any.class) != null) { Object mapObject = field.get(value); if (mapObject instanceof Map<?, ?>) { Map<?, ?> keyValueMap = (Map<?, ?>) mapObject; for (Entry<?, ?> keyValuePair : keyValueMap.entrySet()) { if (keyValuePair.getKey() != null && keyValuePair.getValue() != null) { node.getNode().setAttribute( keyValuePair.getKey().toString(), keyValuePair.getValue().toString()); } } } } } } return super.write(type, value, node, map); } } And this is the Car class with the new annotations: @AnyClass @Root(strict = false, name = "Car") public class Car { @Attribute public double length; @Attribute public String color; @Attribute public int nrOfDoors; @Any public HashMap<String, String> furtherAttributes = new HashMap<String, String>(); } Now the serialisation of the class to xml works. But I do not have a correctly working solution for the deserialisation. Do you have any ideas? Thanks for you help Christian Klotz ------------------------------------------------------------------------------ Monitor your physical, virtual and cloud infrastructure from a single web console. Get in-depth insight into apps, servers, databases, vmware, SAP, cloud infrastructure, etc. Download 30-day Free Trial. Pricing starts from $795 for 25 servers or applications! http://p.sf.net/sfu/zoho_dev2dev_nov _______________________________________________ Simple-support mailing list Sim...@li... https://lists.sourceforge.net/lists/listinfo/simple-support |
|
From: Lumsdon, H. <Hug...@bl...> - 2012-11-14 10:02:05
|
Hi,
I think this has been mentioned, but please can consider adding a really basic framework feature to support un-modifiable collection wrappers using a annotations.
For example:
@ElementList(unmodifiable = true)
private List<xxx> yyyy = new LinkedList<xxx>;
Pretty obvious, but this would make the collection itself immutable (through a Collections.unmodifiableXXX wrapper) once deserialization has completed. We want this feature as we cache and share de-serialized objects and want to restrict developers from doing something stupid i.e. modifying the cached object.
Of course we could wrap the collections manually in a @Commit block (more code to write per object and we have dozens) - or in the getter (wasteful as the wrapper won't get cached) - but it would be much nicer to see this as a framework enhancement.
Thanks,
Hugo.
THIS MESSAGE AND ANY ATTACHMENTS ARE CONFIDENTIAL, PROPRIETARY, AND MAY BE PRIVILEGED. If this message was misdirected, BlackRock, Inc. and its subsidiaries, ("BlackRock") does not waive any confidentiality or privilege. If you are not the intended recipient, please notify us immediately and destroy the message without disclosing its contents to anyone. Any distribution, use or copying of this e-mail or the information it contains by other than an intended recipient is unauthorized. The views and opinions expressed in this e-mail message are the author's own and may not reflect the views and opinions of BlackRock, unless the author is authorized by BlackRock to express such views or opinions on its behalf. All email sent to or from this address is subject to electronic storage and review by BlackRock. Although BlackRock operates anti-virus programs, it does not accept responsibility for any damage whatsoever caused by viruses being passed.
--
BlackRock Advisors (UK) Limited is authorized and regulated by The Financial Services Authority. Registered in England. Registered No:796793. Registered Office: Drapers Gardens, 12 Throgmorton Avenue, London EC2N 2DL.
|
|
From: Christian K. <c....@sp...> - 2012-11-14 09:44:35
|
Hi SimpleXml Team,
I use SimpleXml frequently on android and it is great.
Now I have a question how to do that job:
All XML attributes that are not defined in the Java class with
@Attribute should be serialized and deserialized into a
HashMap<String,String>.
Here is an example:
This is out test class "Car"
@Root(strict = false, name = "Car")
public class Car
{
@Attribute
public double length;
@Attribute
public String color;
@Attribute
public int nrOfDoors;
public HashMap<String, String> furtherAttributes = new
HashMap<String, String>();
}
And this is the serialization test method:
public void testCar() throws Exception
{
Car car = new Car();
car.color = "red";
car.length = 4.3;
car.nrOfDoors = 4;
car.furtherAttributes.put("fuelConsumption", "7.8");
car.furtherAttributes.put("topSpeed", "190");
Serializer serializer = new Persister();
StringWriter stringwriter = new StringWriter();
serializer.write(car, stringwriter);
String xml = stringwriter.toString();
}
The result of the serialization is:
<Car color="red" length="4.3" nrOfDoors="4"/>
So the furtherAttributes of the HashMap are missing. The result should be:
<Car color="red" length="4.3" nrOfDoors="4" fuelConsumption="7.8"
topSpeed="190" />
And the way back should also work:
So if we have a xml like this:
<Car color="green" length="3.3" nrOfDoors="2" topSpeed="190" brand="audi" />
After the deserialization the HashMap "furtherAttributes" should have
the two undefined attributes "topSpeed" and "brand".
I already read the mailing list and some SimpleXml test cases.
So I try implement a new Strategy to solve that problem.
The AnyAttributeRegistryStrategy looks for classes with annotation
"AnyClass" and inside that class searches for the annotation "Any".
The annotation "Any" is used to tag the HashMap, where the futher
attributes should be serialized to.
public class AnyAttributeRegistryStrategy extends RegistryStrategy
{
public AnyAttributeRegistryStrategy(Registry registry)
{
super(registry);
}
@Override
public boolean write(Type type, Object value, NodeMap<OutputNode> node,
@SuppressWarnings("rawtypes") Map map) throws Exception
{
if (value.getClass().getAnnotation(AnyClass.class) != null)
{
for (Field field : value.getClass().getFields())
{
if (field.getAnnotation(Any.class) != null)
{
Object mapObject = field.get(value);
if (mapObject instanceof Map<?, ?>)
{
Map<?, ?> keyValueMap = (Map<?, ?>) mapObject;
for (Entry<?, ?> keyValuePair :
keyValueMap.entrySet())
{
if (keyValuePair.getKey() != null
&& keyValuePair.getValue() != null)
{
node.getNode().setAttribute(
keyValuePair.getKey().toString(),
keyValuePair.getValue().toString());
}
}
}
}
}
}
return super.write(type, value, node, map);
}
}
And this is the Car class with the new annotations:
@AnyClass
@Root(strict = false, name = "Car")
public class Car
{
@Attribute
public double length;
@Attribute
public String color;
@Attribute
public int nrOfDoors;
@Any
public HashMap<String, String> furtherAttributes = new
HashMap<String, String>();
}
Now the serialisation of the class to xml works.
But I do not have a correctly working solution for the deserialisation.
Do you have any ideas?
Thanks for you help
Christian Klotz
|
|
From: Hinkle, C. <Cam...@ni...> - 2012-11-05 18:58:39
|
Hello, Does anyone know the roadmap for Simple? We're using it on a rather large project and I just want to make sure someone will be maintaining for the foreseeable future. It seems like Niall is the only committer; are you still actively working on it or at least addressing bugs that may come up? Thanks, Cameron |
|
From: Niall G. <gal...@ya...> - 2012-11-04 21:30:18
|
Try use @ElementUnion, you can specify a large list of types that are acceptable. Failing that a Converter will work. --- On Sun, 4/11/12, Michael Lipp <mn...@mn...> wrote: > From: Michael Lipp <mn...@mn...> > Subject: [Simple-support] How to handle "ANY" > To: sim...@li... > Received: Sunday, 4 November, 2012, 11:03 AM > Hi, > > trying to use simple XML, I've run into a problem. How am I > going to > handle "ANY"? My schema says: <!ELEMENT extension > ANY>. On the Java side > it's an attribute of type Object. But how can I annotate > it? > > Regards, > > Michael > > > > > ------------------------------------------------------------------------------ > LogMeIn Central: Instant, anywhere, Remote PC access and > management. > Stay in control, update software, and manage PCs from one > command center > Diagnose problems and improve visibility into emerging IT > issues > Automate, monitor and manage. Do more in less time with > Central > http://p.sf.net/sfu/logmein12331_d2d > _______________________________________________ > Simple-support mailing list > Sim...@li... > https://lists.sourceforge.net/lists/listinfo/simple-support > |
|
From: Michael L. <mn...@mn...> - 2012-11-04 20:46:29
|
Hi,
trying to use simple XML, I've run into a problem. How am I going to
handle "ANY"? My schema says: <!ELEMENT extension ANY>. On the Java side
it's an attribute of type Object. But how can I annotate it?
Regards,
Michael
|
|
From: Wolfgang F. <wf...@bi...> - 2012-11-02 18:42:27
|
Dear Niall, as asked in http://stackoverflow.com/questions/12916198/howto-extend-org-simpleframework-xml-with-an-annotation-that-will-write-comments i am trying to add a CommentVisitor using my own @Comment annotation. Please have a look at the code in the question and let us know what might be wrong or whether we need to file a bug report. Please note that the code in your tutorial explaining this does not compile. Yours Wolfgang -- BITPlan - smart solutions Wolfgang Fahl Pater-Delp-Str. 1, D-47877 Willich Schiefbahn Tel. +49 2154 811-480, Fax +49 2154 811-481 Web: http://www.bitplan.de BITPlan GmbH, Willich - HRB 6820 Krefeld, Steuer-Nr.: 10258040548, Geschäftsführer: Wolfgang Fahl |
|
From: Niall G. <gal...@ya...> - 2012-11-01 07:35:41
|
Hi,
I am not sure what you are trying to do here?
Niall
--- On Tue, 30/10/12, Nhat Ngo <phu...@gm...> wrote:
> From: Nhat Ngo <phu...@gm...>
> Subject: [Simple-support] Complex Object Limited Cycle Strategy
> To: sim...@li...
> Received: Tuesday, 30 October, 2012, 11:30 PM
> Hi all,
> Let's say I got the following
> objects:
> Sector.java@Rootpublic class Sector
> {
>
> @Attribute String name;
> @Element Int value;
>
> @ElementList(entry="neighbor") List<Sector>
> neighbours;
>
>
> public Sector(@Attribute name,
> @Element value) { ...
>
> }
>
> public addNeighbour(sector) { ...
>
> }}
> Sectors.javapublic class Sectors
> {
>
> @ElementList List<Sector>
> sectors; ...
> }
> How would I serialize and deserialize the above
> objects into the following sample xml:<Sectors>
> <Sector
> name = "one">
> <value>5</value>
> <neighbours class=...>
>
> <neighbour name="two"
> />
> </neighbours> </Sector>
> <Sector
> name = "two">
> <value>2</value>
> <neighbours class=...>
>
> <neighbour name="one"
> /> <neighbour
> name="three" />
>
>
> </neighbours> </Sector>
>
> ...
> </Sectors>
> Where the Neighbours are referred by designated
> name and not referring to the whole object. I've tried
> CycleStrategy but it seems to refer to every element in
> object and not simply a specific one I needed.
>
> Nhat
>
> -----Inline Attachment Follows-----
>
> ------------------------------------------------------------------------------
> Everyone hates slow websites. So do we.
> Make your web apps faster with AppDynamics
> Download AppDynamics Lite for free today:
> http://p.sf.net/sfu/appdyn_sfd2d_oct
> -----Inline Attachment Follows-----
>
> _______________________________________________
> Simple-support mailing list
> Sim...@li...
> https://lists.sourceforge.net/lists/listinfo/simple-support
>
|