[xstream-user] XStreram moved to GitHub

2015-05-08 Thread Jörg Schaible
Hello folks,

Codehaus will shut down soon and XStream has therefore a new home at Github 
(http://x-stream.github.io/).

This will also affect our mailing lists. We already opened a new one at 
Google Groups, this time one single list for users and developers
(https://groups.google.com/forum/#!forum/xstream-user).

A second list exists for notifications 
(https://groups.google.com/forum/#!forum/xstream-notifications), but it is 
currently in an experimental stage. We might stick with using the GitHub 
facilities alone.

Since you've received this mail, you've been subscribed to one of the old 
mailing lists. However, there's no automated subscription to the new one. So, 
if you're still interested, you're invited to subscribe again.

Cheers,
Jörg

On behalf of the XStream Team

-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Question on serialization

2015-05-05 Thread Jörg Schaible
Hi Abhi,

Abhiram Panyam wrote:

> 
> 
> Jörg Schaible  writes:
> 
>> Hi Abhi,
>> 
>> You can register a JavaBeanConverter to handle OfferVO:
>> 
>> JavaBeanProvider beanProvider = new JavaBeanProvider();
>> xstream.registerConverter(new JavaBeanConverter(xstream.getMapper(),
>> beanProvider, OfferVO.class));
>> 
>> 
> 
> Hi Jorg:
> 
> It appears JavaBeanProvider is an interface. I can't create an object of
> its type using the 'new' operator. Are there any methods that return a
> JavaBeanProvider ?

BeanProvider

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Question on nesting

2015-05-04 Thread Jörg Schaible
Hi Abhi,

Abhiram Panyam wrote:

> I have the following classes
> 
> public class AddressVO {
> 
> private String street;
> private String city;
> private String state;
> private String postalCode;
> private GeographicCoordinates geoCoordinates;
> 
> //constructor, getters and setters
> }
> 
> and
> 
> public class GeographicCoordinates {
> 
> private Double latitude;
> private Double longitude;
> //constructor, getters and setters
> }
> 
> I was able to get the following XML using aliases and attributes
> 
>  postalCode="32256">
> 
>   30.236246
>   -81.594224
> 
> 
> 
> What I need is the latitude and longitude to be attributes of the address
> element...like,
> 
>  postalCode="32256" latitude="30.236246" longitude="-81.594224" />
> 
> I would like to know if this is possible with XStream, and if it is, how.

This is only possible with your own custom converter for AddressVO. See the 
converter tutorial, how to write something like that.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Question on serialization

2015-05-04 Thread Jörg Schaible
Hi Abhi,

Abhiram Panyam wrote:

> I would like to know if I can serialize methods in addition to fields. For
> instance, I have the following class
> 
> public class offerVO {
> 
> private Long offerId;
> private String offer;
> 
> public OfferVO() {
> 
> }
> 
> public Long getOfferId() {
> return offerId;
> }
> 
> public void setOfferId(Long offerId) {
> this.offerId = offerId;
> }
> 
> public String getOffer() {
> return offer;
> }
> 
> public void setOffer(String offer) {
> this.offer = offer;
> }
> 
> public Date getExpirationDate() {
>return Calendar.getInstance().getDate();
> }
> }
> 
> Notice that there is no field called expirationDate in the class, but I
> would like to have it appear in the XML as an attribute called
> 'expirationDate' for the OfferVO element. Please advise.

You can register a JavaBeanConverter to handle OfferVO:

JavaBeanProvider beanProvider = new JavaBeanProvider();
xstream.registerConverter(new JavaBeanConverter(xstream.getMapper(), 
beanProvider, OfferVO.class));

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] RE: Unable to create new JIRA entry

2015-05-04 Thread Jörg Schaible
Hi Rico,

Neubauer. Rico wrote:

> Ah thanks.
> Homepage should get an update then though.

It's in the transition. New home page is not ready.

An update of the old is also not possible, webdav access to site are does 
not/no longer work (at least yesterday).

JIRA is already in read-only mode.

Cheers,
Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: XStream keeps XPath refs to ints, doubles, other Immutables

2015-04-27 Thread Jörg Schaible
Hi Geoff,

Geoff Groos wrote:

> Hey J?rg,
> 
> Thanks for the note about enums, I had it in my head that enum's have been
> in java like that since 1.0. This explains why so many APIs inside java
> are using int constants.
> 
> Anyways, my todos:
> 
>   *
> revert the method signatures to maintain binary compatibility. This means
> I have to use a cast in a couple places but I think its a pretty safe one
> (ie, I'm not sure theres a flow where the XPathStrategy can return a
> marshaller that isn't a XPathMarshaller).

??? Just add the method asking for support of references in Mapper. 
XStream's binary contract in this area is based on derived types of 
MapperWrapper. There's no cast necessary.

>   *
> I'll remove the enums and use static integers (maybe with an odd range of
> numbers so-as to allow for an assertion that the caller used the proper
> integers)

Just a boolean. Support references for a type or not.

> And of course when I send you any diffs I'll remove the class files --that
> was simply me bashing your build system into a repo that I didn't really
> spend much time setting up. I just wanted a concise list of the diffs,
> which a github pull-request provides.

OK. Note, xtream repo is now at x-stream.github.com/xstream.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: XStream keeps XPath refs to ints, doubles, other Immutables

2015-04-27 Thread Jörg Schaible
Hi Geoff,

sorry for being silent, but we're busy getting several projects out of the 
Haus before it shuts down.

Geoff Groos wrote:

> Hey guys,
> 
> So I whipped together this quick patch:
> https://github.com/Groostav/XStream-GG/pull/1
> 
> I think I'd like to modify it to remove the `Context` object --its too big
> a klooge to have the configuration need to know if the caller is
> Unmarshalling or Marshalling. I'll get around to that today.
> 
> let me know what you think.

I had a short look at the diffs. Actually they should not contain any cruft 
(.class files, ...).

For the implementation: I would have used the Mapper interface also as 
"entry" point. However, you may not modify a method, you have to add a new 
one instead (resp. overload a method) to keep binary compatibility. The 
master branch is already for XStream 1.5.x with a minimum requirement of 
Java 6.

However, I assume, you're interested in getting this into the 1.4.x branch 
(Java 1.4.x compatible). Therefore you cannot use a Java enum at all, we 
cannot backport it. Basically all you need is a boolean flag for the 
immutable types that do not support references at all. We have no intentions 
to support multiple modes here, it's just a compatibility helper.

Thanks for your effort so far,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: XStream keeps XPath refs to ints, doubles, other Immutables

2015-04-21 Thread Jörg Schaible
Hi Geoff,

Geoff Groos wrote:

> I'm on XStream 1.4.7 (I'll get myself current in a moment)
> 
> I'm looking at line 67 of the AbstractReferenceUnmarshaller where it's
> putting the integer `10` in as a value for the reference-key
> ".../myModelMatrixClass/widthOfMatrix". The field corresponding to that
> path is an 'int'.
> 
> the myModelMatrix type does use a custom converter which extends the
> ReflectionConverter, but it uses the stock `unmarshalField` method to
> unmarshall that field, which in turn is hitting the
> 'abstractReferenceUnmarshaller' to unmarshall the '10' value at the
> element 10
> 
> I hope I'm describing this accurately. I could start putting together an
> SSCCE if it would help.

OK. My bad, I've looked at the marshaller only. Basically you're right, but 
if we throw away the references for immutables, we might introduce a 
compatibility problem:

 %< =
UUID[] uuidArray = new UUID[2];
uuidArray[0] = uuidArray[1] = UUID.randomUUID();
XStream xstream = new XStream();
String xml = xstream.toXML(uuidArray);

// unmarshal in later version of application with a changed setup:
XStream xstream = new XStream();
xstrea.addImmutable(UUID.class);
xstream.fromXML(xml); // XStreamException, reference not found
 %< =

See, I've already set UUID as immutable for 1.4.9. If we drop also the 
references to any immutable, anybody with an XML containing a reference to a 
UUID will fail at deserialization. :-/

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: XStream keeps XPath refs to ints, doubles, other Immutables

2015-04-21 Thread Jörg Schaible
Hi Geoff,

Geoff Groos wrote:

> Hey guys,
> 
> Deserialization of our model (using XStream) currently requires upwards of
> 500mb of memory. I’ve been tasked with fixing this since, in the worst
> case, our model is a matrix with an upper bound of 10,000 rows and 1,000
> columns (10mb big).
> 
> Looking at our deserialization process under the profiler, I noticed that
> XStream’s xpath map was consuming upwards of 95% of that space. Digging in
> a little deeper, I noticed the XPath map keeping paths to Booleans and
> Integers.
> 
> What’s the purpose of keeping an XPath entry to an instance of an
> immutable type?
> 
> In other words, If I had
> 
> class XPathAnnoyer{
> public Integer x; //using Object Integer, an immutable type.
> public Integer y;
> }
> 
> Integer intInstance = new Integer(20);
> XPathAnnoyer instance = new XPathAnnoyer();
> instance.x = intInstance;
> instance.y = intInstance;
> 
> String result = xstream.serialize(instance);
> 
> Result would be
> 
> 20
> 20
> 
> 
> and the xpath map will contain the (completely useless entry)
> “Integer@ABC123” -> “root/dotdotdot/XPathAnnoyer/x”
> 
> So when would that entry ever get used? Why bother keeping it?
> 
> My argument against keeping it is that I’m hoping I can get my memory
> profile down significantly.
> 
> Let me know if my understanding of this issue is not correct, or if
> there’s some obvious case I’m overlooking.

Which xpath map you're talking about and which XStream version? XStream 
keeps the references in the AbstractReferenceMarshaller.references and that 
collection does not contain references to immutable types.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: XStream fails to de-serialize java.util.HashSet

2015-04-13 Thread Jörg Schaible
Tobias Gierke wrote:

> 
>> It *seems* like the issue was caused by an interesting interaction
>> between the converters but I admit I know far too much about XStreams
>> inner workings to make sense of this.
> This should've read "[...] know far too little" ofc ;)

;-)

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: XStream fails to de-serialize java.util.HashSet

2015-04-13 Thread Jörg Schaible
Hi Tobias,

Tobias Gierke wrote:

[snip]
 
> Thanks for your quick response ! We changed too many things
> unfortunately :/ We upgraded from XStream 1.4.3 to 1.4.8 because of the
> JDK8 fixes and at the same time also did a lot of changes to our
> application.
> 
> I just managed to "fix" the issue by changing the priorities and set of
> converters I registered like so:
> 
> == 1.4.3 =
> 
>  final XStream xstream = new XStream( new StaxDriver() ) {
>  @Override
>  protected MapperWrapper wrapMapper(MapperWrapper next) {
>  return new WicketProxyMapper( new CGLIBMapper( new
> HibernateMapper(next) ) );
>  }
>  };
> 
>   xstream.registerConverter( new WicketProxyConverter() ,
> XStream.PRIORITY_VERY_HIGH );
>   xstream.registerConverter( new EnumConverter() ,
> XStream.PRIORITY_VERY_HIGH );
>  xstream.registerConverter(new
> HibernatePersistentCollectionConverter(xstream.getMapper()) ,
> XStream.PRIORITY_VERY_HIGH );
>  xstream.registerConverter(new
> HibernatePersistentMapConverter(xstream.getMapper()) ,
> XStream.PRIORITY_VERY_HIGH );
>  xstream.registerConverter(new
> HibernatePersistentSortedMapConverter(xstream.getMapper()) ,
> XStream.PRIORITY_VERY_HIGH );
>  xstream.registerConverter(new
> HibernatePersistentSortedSetConverter(xstream.getMapper()) ,
> XStream.PRIORITY_VERY_HIGH );
>  xstream.registerConverter(new HibernateProxyConverter() ,
> XStream.PRIORITY_VERY_HIGH );
>  xstream.registerConverter(new
> CGLIBEnhancedConverter(xstream.getMapper(),
> xstream.getReflectionProvider() , getClass().getClassLoader() ) );
>  xstream.registerConverter( new
> SerializableConverter(xstream.getMapper(),
> xstream.getReflectionProvider() , getClass().getClassLoader() ) );
> 
> 
> == 1.4.8 =
> 
>  final XStream xstream = new XStream( new StaxDriver() ) {
>  @Override
>  protected MapperWrapper wrapMapper(MapperWrapper next) {
>  return new WicketProxyMapper( new CGLIBMapper( new
> HibernateMapper(next) ) );
>  }
>  };
> 
>  xstream.registerConverter( new WicketProxyConverter() ,
> XStream.PRIORITY_VERY_HIGH );
>  xstream.registerConverter(new
> HibernatePersistentCollectionConverter(xstream.getMapper()) );
>  xstream.registerConverter(new
> HibernatePersistentMapConverter(xstream.getMapper()) );
>  xstream.registerConverter(new
> HibernatePersistentSortedMapConverter(xstream.getMapper()) );
>  xstream.registerConverter(new
> HibernatePersistentSortedSetConverter(xstream.getMapper()) );
>  xstream.registerConverter(new HibernateProxyConverter() );
>  xstream.registerConverter(new
> CGLIBEnhancedConverter(xstream.getMapper(),
> xstream.getReflectionProvider() , getClass().getClassLoader() ) );
> 
> It *seems* like the issue was caused by an interesting interaction
> between the converters but I admit I know far too much about XStreams
> inner workings to make sense of this.


The most problematic action was/is the registration of the 
SerializationConverter with normal priority. That will prefer it over any 
other converter with same priority (see default priority in  
http://xstream.codehaus.org/converters.html) i.e. any Serializable with a 
readObject/writeObject method will now be handled by the generic 
SerializationConverter instead of the more specialized one (e.g. the 
CollectionConverter for a HashSet).

Try yourself:

 HashSet hs = new HashSet<>();
 hs.add("test");

 XStream xstream = new XStream();
 xstream.registerConverter(
   new SerializableConverter(xstream.getMapper(),
   xstream.getReflectionProvider(), xstream.getClassLoaderReference()));
 System.out.Println(xstream.toXML(hs));
 System.out.Println(new XStream().toXML(hs)); // vanilla instance

That should make a difference.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: XStream fails to de-serialize java.util.HashSet

2015-04-13 Thread Jörg Schaible
Hi Tobias,

Tobias Gierke wrote:

> Hi,
> 
> We recently started getting weird XStream errors on code that was
> previously working fine. IMHO some (seemingly unreleated) change causes
> the serialization to output bad XML and this in turn makes the
> deserialization fall over later on.
> 
> The error message I'm getting is:
> 
> com.thoughtworks.xstream.converters.ConversionException: Cannot
> deserialize object with new readObject()/writeObject() methods
>  Debugging information 
> class   : java.util.HashSet
> required-type   : java.util.HashSet
> converter-type  :
> com.thoughtworks.xstream.converters.reflection.SerializableConverter
> path:
> 
/com.vodecc.voipmng.boundary.wicket.streamsearch.StreamSearchResultsPage/children/com.vodecc.voipmng.boundary.wicket.general.UserInfoPanel/children/com.vodecc.voipmng.boundary.wicket.general.UserInfoPanel$UserEditableFragment/children/children/data/org.apache.wicket.model.PropertyModel/target/roles
> line number : 1
> class[1]: com.vodecc.voipmng.core.usermng.entity.CVod_UserBean
> converter-type[1]   :
> com.thoughtworks.xstream.converters.reflection.ReflectionConverter
> class[2]: org.apache.wicket.model.PropertyModel
> class[3]: [Ljava.lang.Object;
> converter-type[2]   :
> com.thoughtworks.xstream.converters.collections.ArrayConverter
> class[4]: org.apache.wicket.markup.html.basic.Label
> class[5]:
> com.vodecc.voipmng.boundary.wicket.integration.StrutsActionLink
> class[6]:
> 
com.vodecc.voipmng.boundary.wicket.general.UserInfoPanel$UserEditableFragment
> class[7]:
> com.vodecc.voipmng.boundary.wicket.general.UserInfoPanel
> class[8]:
> com.vodecc.voipmng.boundary.wicket.streamsearch.StreamSearchResultsPage
> version : not available
> 
> The weird thing is this:
> 
> I created a stand-alone unit-test that serializes & deserializes a
> org.apache.wicket.model.PropertyModel that wraps a "CVod_UserBean"
> instance with a non-empty "roles" HashSet and it works just fine (see
> attached file working.xml). It's just not working when serializing the
> whole Apache Wicket page.
> 
> As a side note, the "roles" attribute actually holds a Hibernate
> PersistentSet. I'm using the HibernatePersistentCollectionConverter to
> handle this , after changing my unit-test to use PersistentSet instead
> of java.util.HashSet it still working correctly.
> 
> Comparing the working/broken (see attachments) I see that the *broken*
> XML lacks 'serialization='custom' attributes ... what is the meaning of
> these attributes and what might be the reason why their missing in the
> broken XML (both using an XStream instance with identical
> mappers/converters) ?
> 
> This is with XStream 1.4.8 and JDK 1.8.0_40 on 64-bit Linux.

You face a version problem in your object model. The problem simply 
indicates that the type of the instance used in the "roles" field of 
CVod_UserBean is different now.

Compare the following output:

 HashSet hs1 = new HashSet<>();
 hs1.add(EVF_Permission.EXPORT_SIP_TRUNKS);
 HashSet hs2 = new HashSet<>() {};
 hs2.add(EVF_Permission.EXPORT_SIP_TRUNKS);
 System.out.println(xstream.toXML(hs1));
 System.out.println(xstream.toXML(hs2));

You will see in the similar differences to your XML examples.

The first instance is actually handled by the CollectionConverter while the 
second instance is handled by the SerializationConverter. Therefore you see 
a different XML representation.

So, what has actually be changed?

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: XStream: is it possible to re-set alias on the fly?

2015-04-13 Thread Jörg Schaible
Hi Alex,

Alex Y. Matiash wrote:

> Hello world!
> 
> I've tried to google as hard as I can, but I didn't find an answer for my
> problems.
> 
> 1. The problem is that due to some reason our protocol has identical XML
> structure for all packets, so I can't create permanent aliases, neither
> using annotations nor by calling XStream.alias(). Also I have to mention
> that calling XStream.processAnnotations() before each packet parsing is
> not appropriate because it is (AFAIK) "heavy" operation. I tried to call
> xStream.alias("A", ClassA.class) (ClassA, ClassB, ClassC, etc) on the fly
> before parsing each packet, but nothing (good) happened. Then I've digged
> into the sources, and found that ClassAliasingMapper.addTypeAlias() only
> adds aliases, and in case of any duplicates (both name and class) there is
> no way to removed old alias. Is it true, or I'm missing something?

Yes, this is true.

> If it
> is true there is an another question - is it possible to do anything in
> such case (the same XML structure for all packets)? In case if it is
> impossible now - I would be extremely grateful if somebody can add
> something like XStream.removeAlias();

No. This is not possible. XStream is designed for concurrent 
(un-)marshalling processes. Modifying the configuration on-the-fly will 
cause severe and unpredictable side-effects. XStream is supposed to be 
immutable after configuration.
> 
> 2. I have very simple XML with structure: , but doing
> XStream.alias("D", ClassD.class); XStream.alias("I', ClassI.class);
> results in an exception telling me that there is no class registered to
> save contents of tag "I".

Right.

> Only XStream.alias("D", ClassD.class);
> XStream.aliasField("I', ClassD.class, "fieldI"); works as required. Why it
> is impossible to just set two aliases for two pairs tag-class?

XStream is "Java to XML and back", i.e. your XML represents a complete 
object graph. You have defined that your XML root is represented by a class:

class ClassD {
...
}

Since ClassD contains now fields, the inner tags reflect these names. It 
cannot represent a type (it's already defined by the field definition). In 
your case it is a field of ClassD named "I" or whatever name you have used 
with defining a field alias.

It looks like you try to setup XStream to read an incoming XML. Actually 
this is not recommended at all. Always go the other way round. Build your 
Java object model and marshal it to XML. If the resulting XML matches the 
required structure, you will also be able to read it. It is an error-prone 
and annoying task to setup an XStream instance just by looking at the XML 
and simply guessing what XStream might do with it while unmarshalling.

> Thanks to everybody in advance.

Cheers,
Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: java.time does not appear to serialize/deserialize properly

2015-04-13 Thread Jörg Schaible
Hi Geoff,

Geoff Groos wrote:

> Hey guys,
> 
> I’m wondering what you guys think of XStream + the new (java 1.8)
> java.time library.

Someone has to start :-)

> I’ve started replacing joda.time uses with java.time ones (as encouraged
> by the Joda time guys themselves) and I only noticed when I ran my
> persistence tests that anything causing XStream to touch a
> java.time.Instant instance would fail.
> 
> A simple test to reproduce:
> 
> private static class ClassWithTimestamp{
> public final Instant timestamp = Instant.now();
> }
> 
> @Test
> public void
> when_serializing_a_timestamp_xstream_should_have_no_trouble(){
> //setup
> XStream vanillaXStream = new XStream();
> ClassWithTimestamp originalInstance = new ClassWithTimestamp();
> 
> //act
> String serialized = vanillaXStream.toXML(originalInstance);
> ClassWithTimestamp deserialized = (ClassWithTimestamp)
> vanillaXStream.fromXML(serialized);
> 
> //assert
> 
assertThat(deserialized.timestamp).isEqualTo(originalInstance.timestamp);
> }
> 
> 
> Thoughts?

Well, actually XStream should have been able to marshal/unmarshal this, but 
I'll have a look.
 
> I’m implementing custom converters now, and since java.time is so much
> more interoperable with the ISO 8601 spec than that worse-than-useless
> java.util.Date stuff, I’m thinking I’ll register these as immutable and
> have them serialize and deserialize to nice ISO strings.

That would be definitely the best approach.

> I’d be honored if I could push that stuff upstream to you guys!

A very welcome addition to XStream, it would be nice to get such a 
contribution!

Cheers,
Jörg

Note, XStream is currently in the transition from Codehaus to Github. If 
you're ready to contribute, please give a note here that we may point you to 
the proper place.


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Help unmarshalling Collection/TreeSet

2015-04-01 Thread Jörg Schaible
Hi Luiz,

Felipe wrote:

> Good morning everyone,
> 
> I need help on something:
> 
> I'm trying to unmarshall from a huge XML into ValueObjects, but I keep
> getting erros, and I'm trying like crazy to make this work, but it has
> been a little hard. I've been using XStream for years and it always worked
> fine, but now I'm getting slapped in the face.
> 
> This huge ValueObject contains lots of primitive and complex types inside
> it, and it's complex types contains Collections of TreeSet's.
> 
> I've been managed to marshall and unmarshall Collections of ArrayLists
> well, but now with this Collections of TreeSets I just can't make it work.
> 
> Errors I've been getting:
> 
> java.lang.InstantiationError: java.util.Collection
> 
> Things I've tried:
> xStream.addDefaultImplementation(Collection.class,
> MyTypeThatContainsTheCollection);

This does not make sense. Here you've told XStream that it should use a 
MyTypeThatContainsTheCollection anywhere it would normally look out for a 
Collection. Somehow I doubt that MyTypeThatContainsTheCollection *is* a 
Collection at all.

> xStream.addImplicitCollection(MyTypeThatContainsTheCollection, fieldName);

Here you have told XStream that the Collection stored in "fieldName" is 
implicit i.e. all its elements are siblings to any other field of 
MyTypeThatContainsTheCollection.

> xStream.alias("collectionFieldName", ArrayList.class);

You have told XStream now, that it should use the name "collectionFieldName" 
for the type name ArrayList. However, since ArrayList is the default 
implementation of a List and a list's alias is "list", the alias for 
ArrayList is hardly used at all.

> Whats is the thing about XStream and Collections of TreeSet?
> I'm afraid I can't explain well where my problem is, but I do not know
> anymore. I've been trying this work for more than one week, without
> success. What should I know about XStream and Collection/TreeSet. Why I
> can make it work well with Collection of ArrayList?

It depends on the declaration of the field "fieldName" in 
MyTypeThatContainsTheCollection. The default implementation of that 
declaration determines the real type of the deserialized collection.

> I've been researching google exaustively, and I alaways see examples of
> converters, but I just can't figure it out. Should this be the solution
> for my problem? Should I implement a converter?

Well, without knowing your real Java declarations nor the XML, I cannot say 
a lot more. Did you at least use the XStream to serialize your object model? 
Only if that XML output matches the format of the XML you want to read, you 
have at least a chance. Setting up an XStream solely by looking at the input 
is very, very, error-prone any annoying, as you have already learned. Do it 
always the other way round.

Cheers,
Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] RE: Re: Make UUID an Immutable type by default

2015-03-04 Thread Jörg Schaible
Hi Geoff,

Geoff Groos wrote:

> Thanks Jörg,
> 
> I created an account but have run into some http:500s and what-not from
> jira while creating my account. I'll create the issue when I get all this
> stuff sorted out.
> 
> The second question I have, semi-related, is how would you guys suggest
> doing generational (ie cross-model-version) testing?
> 
> What I'd like to do is have tests like this:
> 
> public static class TestFixture{
> 
> public static class MyModel{ //v1
> Public int x;
> Public int y;
> }
> 
> //And attempt to deserialize (using our moderately customized xstream
> serializer) it as
> 
> public static class MyModel{ //v2
> Public int x;
> Public int y;
> Publix int z;
> }
> 
> //in something like this
> @Test
> public void
> 
when_we_added_an_extra_int_field_for_feature_1234_we_didnt_break_anything_because_our_deserialization_flow_is_so_nifty()
{
>//setup
> OurSerializerThatDelegatesToXStream serializer =
> testHarness.provideSerializer();
> 
> //act
> String serialized = serializer.serialize(makeVersion1OfMyModel());
> MyModel myModelV2 = serializer.deserialize(serialized);
> 
> //assert
> assertThat(myModelV2.z).followsProperDomainLogic();
> }
> }
> 
> But of course Javac is going to complain about 2 'MyClass'es.
> 
> Any suggestions?

Why don't you simply take the XML representation of model 1 and deserialize 
it into model 2? Why do you still need to generate the XML representation of 
model 1?

> I was thinking about trying using 2 different canonical names (so MyClass1
> and MyClass2), and then add an entry to the aliasMap as part of the setup
> logic to tell XStream that MyClass1 is-a MyClass2.
> 
> But since that doesn’t involve nearly enough overly complex code, the
> other thing I was thinking of doing is copy-pasting class files around and
> then manually loading via some stupidly sophisticated mechanism. With a
> couple extra ant targets I could probably even make this bearable.

The strategy to handle newer versions of a class depends on the type of 
modification. There's no general rule.

See http://xstream.codehaus.org/faq.html#Serialization_newer_class_versions 
for some ideas.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Using XStream 1.4.8 in android 4.4 fails.

2015-02-22 Thread Jörg Schaible
Hi Bruce,

Bruce Link wrote:

> I believe that xStream being compiled against Java 8 removes the ability
> for XStream to be used as a drop in module in android 4.4.
> 
> When I use 1.4.8 in eclipse as a module for my Android 4.4 project, I
> receive a compile error along the lines of:
> 
> UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dx.cf.iface.ParseException:
> bad class file magic (cafebabe) or version (0034.)
> 
> Which I understand is due to an incompatible JDK version see:
> http://stackoverflow.com/questions/24795161/how-to-use-a-java-8-library-with-android
> 
> This error does not appear when using version 1.4.7.
> 
> My apologies if this is a known issue already, I did my best to review
> the mailing list and bug tracker.

I was unaware of Android not supporting Java 8. However, you can simply 
remove the class files for the LambdaConverter and the LambdaMapper from the 
archive. They are only used with a Java 8 runtime.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: handle xml empty tag

2015-02-22 Thread Jörg Schaible
Hi,

manoj wrote:

> I have xml with empty tag. while calling below code i am getting
> conversion exception.
> public static   T xmlToVoConversion(String data ,  Class
> genericType) {
> XStream stream = new XStream( );
> stream.processAnnotations(genericType);
> T convertedObject = (T) stream.fromXML(data);
> logger.info(convertedObject);
> return convertedObject;
> }
> 
> I need solution with customer convertor.


It depends completely on the type you're unmarshalling. For some is an empty 
value valid, for others it is not.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] [ANN] XStream 1.4.8 released

2015-02-18 Thread Jörg Schaible
Hello followers,

a new maintenace release of XStreeam has been released as version 1.4.8. It is 
supposed to be a simple drop-in replacement. Some minor bugs have been fixed, 
improves the support for serializable lambda expressions in  Java 8 and 
detects Java 9. Support is still available for 1.4 as minimal Java runtime.

Have a look yourself:
http://xstream.codehaus.org/downloads.html

Enjoy,
XStream Committers

-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Make UUID an Immutable type by default

2015-02-18 Thread Jörg Schaible
Hi Geoff,

Geoff Groos wrote:

> Hey guys,
> 
> We’re just about to go to version 1.0, so I’m running over every piece of
> tech-debt I can think of to make sure all my ducks are in a row, and I
> found this in our project file (an XML serialized model):
> 
>   
> b723fec2-50f9-45fa-9a41-
fee8d022b544
> 
>   
>   
>  reference="../../ProjectState.ImmutableMomento/associatedRunId"/>
> 
> I cant think of a good reason for a UUID not to be immutable by default.
> Doing oneID == anotherID has to be as taboo as aString == anotherString to
> anybody whose willing to use a UUID object, meaning I don't think there’s
> any reason to preserve reference equality in serialization.

You're absolutely right. Can you open a JIRA ticket to track the issue, 
please? Simply follow instructions at 
http://xstream.codehaus.org/issues.html

Cheers,
Jörg

Sad to say, but 2 hours earlier, and it would already have been part of the 
new release :-/


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: ISO8601GregorianCalendarConverter invalid conversion between time zones

2015-02-15 Thread Jörg Schaible
Hi Jason,

Jason Steenstrapickens wrote:

> Hi,
> 
> 
> We have recently been experiencing issues deserialising XML with specific
> time zones. This only seems to be occurring on Windows where the time zone
> does not have an Id that is in the available list of Ids. It seems this is
> caused by Windows not using the Olson time zone database.
> 
> 
> For example, when setting the system time zone to GMT-12:00 and calling
> TimeZone.getDefault().getID() the JRE will return "GMT-12:00". Joda time
> knows about this and if you try and use this to convert to a Joda
> DateTimeZone it will strip of the "GMT" prefix and return a time zone with
> Id of "-12:00".
> 
> 
> The problem seems to be in
> 
com.thoughtworks.xstream.converters.extended.ISO8601GregorianCalendarConverter.fromString(String)?.
> This has the following code:
> 
> ...
> String timeZoneID = TimeZone.getDefault().getID();
> for (int i = 0; i < formattersNoUTC.length; i++ ) {
> try {
> DateTimeFormatter formatter =
> formattersNoUTC[i].withZone(DateTimeZone.forID(timeZoneID)); ...
> } ...
> }
> ...
> 
> This code is getting the time zone Id from the JRE and then passing this
> to DateTimeZone.forID to convert to a Joda time zone. This doesn't work
> when the time zone Id is not in the available list of Ids. There is an
> invalid assumption that the same time zone Id from the JRE can be used to
> get the Joda time zone.
> 
> There is actually no need to even use the Id here, the code could simply
> be: ...
> final DateTimeZone dtz = DateTimeZone.getDefault();
> for (int i = 0; i < formattersNoUTC.length; i++ ) {
> try {
> DateTimeFormatter formatter = formattersNoUTC[i].withZone(dtz);
> ...
> } ...
> }
> ...
> 
> This ignores the problem entirely and uses the time zone reported by Joda
> directly.

Can you open a JIRA issue please? Simply follow instructions at 
http://xstream.codehaus.org/issues.html

It will help us to track the changes for an upcoming release.

Thanks,
Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Question about Using XStream

2015-01-14 Thread Jörg Schaible
Hi Miccio,

郝强_BYR wrote:

> Hi,
> I use xstream to read and write xml file in my project, and I
> encounter a problem. In the project, there's an xml configuration
> file, but it is used by two  programs.  The other program may add some
> unknown tags which are the tags of xml file that don't have the
> corresponding class defined in my java program, but they are useful in
> the other program. The aim is to reserve‍ these strange tags when the
> classes are wrote back to xml file. It means the strange tags should
> be wrote back, though I don't need them in my program. I have learnt
> your tutorials online and many blogs. Now I can discard these unknown
> tags, so there will not be any exceptions when the xstream encounter
> unknown tags, but when it is wrote back, these tags don't appear in
> the xml file any more.‍
>I want to ask whether there is a method that it can reserve these
>unknow tags (the tags of xml file that don't have the corresponding
>class defined in my java program‍) in the xml file after my java
>program read the file and write back.
> 
> 
>Thanks. Waiting for your reply.
> 
> 
> Best regards!
> miccio

There's no support for this in XStream. XStream is "from Java to XML and 
back" and therefore not designed to keep unknown elements, because they are 
not part of the Java model. Either you enhance your model or you may have a 
look at XSTR-474. Peter Knego once developed an enhancement with a similar 
functionality with certain limitations.

Cheers,
Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: Lambda deserialization failing with XStream 1.4.7 and JDK 1.8ea40 (64-bit)

2015-01-07 Thread Jörg Schaible
Hi Tobias,

Tobias Gierke wrote:

> Hi Jörg,
> 
> I created a JIRA issue: http://jira.codehaus.org/browse/XSTR-767

thanks. Can you also provide the generated XML for the relevant structure?

> Thanks for looking into this!

Cheers,
Jörg

> 
> Cheers,
> Tobias
> 
> 
>> Hi Tobias,
>>
>> it seems you're the first one who tries to serialize something like that.
>> Please open a JIRA issue and I try to look into it in the next two weeks.
>>
>> Cheers,
>> Jörg
>>
>> Tobias Gierke wrote:
>>
>>> Hi,
>>>
>>> It seems we're not able to deserialize Lambda expressions with XStream
>>> 1.4.7
>>>
>>> The code in question looks roughly like this:
>>>
>>> @FunctionalInterface
>>> public interface Visible extends Serializable {
>>>   public boolean isVisible();
>>> }
>>>
>>> public interface IMenuItem extends Serializable {
>>>   // ... stuff omitted ...
>>> }
>>>
>>> public abstract class AbstractMenuItem implements IMenuItem {
>>>   private final Visible visibilityFunction;
>>>   // ... stuff omitted ...
>>> }
>>>
>>> The method that is invoked with lambda expressions (that later get
>>> stored in the 'visibilityFunction' field of an AbstractMenuItem subclass
>>> instance) looks like this:
>>>
>>> public  void addEntry(String resourceLabel , Class
>>> pageClazz,Visible visibilityFunction);
>>>
>>> Since the Visible interface extends Serializable , the compiler
>>> generates code for a serializable Lambda (and in fact it does, I checked
>>> the generated .class file with javap).
>>>
>>> The code used to setup XStream looks like this:
>>>
>>>   private XStream createXStream()
>>>   {
>>>   final XStream xstream = new XStream( new StaxDriver() ) {
>>>   @Override
>>>   protected MapperWrapper wrapMapper(MapperWrapper next) {
>>>   return new WicketProxyMapper( new CGLIBMapper( new
>>> HibernateMapper(next) ) ); //
>>>   }
>>>   };
>>>
>>>   // override the built-in DynamicProxyConverter that chokes on
>>> Apache Wicket proxies
>>>xstream.registerConverter( new WicketProxyConverter() ,
>>> XStream.PRIORITY_VERY_HIGH );
>>>
>>>   // register Hibernate-specific converters
>>>   xstream.registerConverter(new HibernateProxyConverter());
>>>   xstream.registerConverter(new
>>> HibernatePersistentCollectionConverter(xstream.getMapper()));
>>>   xstream.registerConverter(new
>>> HibernatePersistentMapConverter(xstream.getMapper()));
>>>   xstream.registerConverter(new
>>> HibernatePersistentSortedMapConverter(xstream.getMapper()));
>>>   xstream.registerConverter(new
>>> HibernatePersistentSortedSetConverter(xstream.getMapper()));
>>>
>>>   // register CGLLib converters
>>>   xstream.registerConverter(new
>>> CGLIBEnhancedConverter(xstream.getMapper(),
>>> xstream.getReflectionProvider() , getClass().getClassLoader() ) );
>>>
>>>   return xstream;
>>>   }
>>>
>>>
>>> Before I start diving into the world of invokedynamic and method handles
>>> , did anybody else encounter this issue and knows how to solve it ?
>>>
>>> Cheers,
>>> Tobias
>>>
>>>
>>> com.thoughtworks.xstream.converters.ConversionException:
>>>
>> 
com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$$Lambda$124/1803727536
>>> :
>>>
>> 
com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$$Lambda$124/1803727536
>>>  Debugging information 
>>> message :
>>>
>> 
com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$$Lambda$124/1803727536
>>> cause-exception :
>>> com.thoughtworks.xstream.mapper.CannotResolveClassException
>>> cause-message   :
>>>
>> 
com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$$Lambda$124/1803727536
>>> class   :
>>> com.vodecc.voipmng.boundary.wicket.general.PageWithHeaderAndFooter$11
>>> required-type   :
>>> com.vodecc.voipmng.boundary.wicket.general.PageWithHeaderAndFooter$11
>>> converter-type  :
>>> com.thoughtworks.xstream.converters.reflection.ReflectionConverter
>>> path:
>>>
>> 
/com.vodecc.voipmng.boundary.wicket.trunkmonitor.TrunkMonitorPage/children/com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$1/children/com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$1$1[2]/children/com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$SubMenuList/children/children/org.apache.wicket.markup.html.list.ListItem/children/children/com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$NestedListEntry$1/children/org.apache.wicket.markup.html.list.ListItem[3]/children/children/val$visibilityFunction
>>> line number : 1
>>> class[1]:
>>> com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$SimpleListEntry
>>> class[2]: org.apache.wicket.markup.html.list.ListItem
>>> class[3]: [Ljava.lang.Object;
>>> converter-type[1]   :
>>> com.thoughtworks.xstream.converters.collections.ArrayConverter
>>> class[4]:
>>> 
com.vodecc.

[xstream-user] Re: 2 Doubts

2015-01-02 Thread Jörg Schaible
Hi Fabio,

Fabio Ebner wrote:

> 1 - I'm using this code to generate my xml file:

[snip]

> but i want to know if its possible to i add the  encoding="ISO-8859-1"?>
> at beginning of my file? how?

This is documented:
http://xstream.codehaus.org/faq.html#XML_write_XML_declaration

> 2 - have one easy way to transform some char during the creation of my
> file? i need to transform this chars:
> 
>> in <
> < in >
> & in &
> " in "
> ' in '

This is done automatically ... ?

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Lambda deserialization failing with XStream 1.4.7 and JDK 1.8ea40 (64-bit)

2014-12-26 Thread Jörg Schaible
Hi Tobias,

it seems you're the first one who tries to serialize something like that. 
Please open a JIRA issue and I try to look into it in the next two weeks.

Cheers,
Jörg

Tobias Gierke wrote:

> Hi,
> 
> It seems we're not able to deserialize Lambda expressions with XStream
> 1.4.7
> 
> The code in question looks roughly like this:
> 
> @FunctionalInterface
> public interface Visible extends Serializable {
>  public boolean isVisible();
> }
> 
> public interface IMenuItem extends Serializable {
>  // ... stuff omitted ...
> }
> 
> public abstract class AbstractMenuItem implements IMenuItem {
>  private final Visible visibilityFunction;
>  // ... stuff omitted ...
> }
> 
> The method that is invoked with lambda expressions (that later get
> stored in the 'visibilityFunction' field of an AbstractMenuItem subclass
> instance) looks like this:
> 
> public  void addEntry(String resourceLabel , Class
> pageClazz,Visible visibilityFunction);
> 
> Since the Visible interface extends Serializable , the compiler
> generates code for a serializable Lambda (and in fact it does, I checked
> the generated .class file with javap).
> 
> The code used to setup XStream looks like this:
> 
>  private XStream createXStream()
>  {
>  final XStream xstream = new XStream( new StaxDriver() ) {
>  @Override
>  protected MapperWrapper wrapMapper(MapperWrapper next) {
>  return new WicketProxyMapper( new CGLIBMapper( new
> HibernateMapper(next) ) ); //
>  }
>  };
> 
>  // override the built-in DynamicProxyConverter that chokes on
> Apache Wicket proxies
>   xstream.registerConverter( new WicketProxyConverter() ,
> XStream.PRIORITY_VERY_HIGH );
> 
>  // register Hibernate-specific converters
>  xstream.registerConverter(new HibernateProxyConverter());
>  xstream.registerConverter(new
> HibernatePersistentCollectionConverter(xstream.getMapper()));
>  xstream.registerConverter(new
> HibernatePersistentMapConverter(xstream.getMapper()));
>  xstream.registerConverter(new
> HibernatePersistentSortedMapConverter(xstream.getMapper()));
>  xstream.registerConverter(new
> HibernatePersistentSortedSetConverter(xstream.getMapper()));
> 
>  // register CGLLib converters
>  xstream.registerConverter(new
> CGLIBEnhancedConverter(xstream.getMapper(),
> xstream.getReflectionProvider() , getClass().getClassLoader() ) );
> 
>  return xstream;
>  }
> 
> 
> Before I start diving into the world of invokedynamic and method handles
> , did anybody else encounter this issue and knows how to solve it ?
> 
> Cheers,
> Tobias
> 
> 
> com.thoughtworks.xstream.converters.ConversionException:
> 
com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$$Lambda$124/1803727536
> : 
> 
com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$$Lambda$124/1803727536
>  Debugging information 
> message :
> 
com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$$Lambda$124/1803727536
> cause-exception :
> com.thoughtworks.xstream.mapper.CannotResolveClassException
> cause-message   :
> 
com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$$Lambda$124/1803727536
> class   :
> com.vodecc.voipmng.boundary.wicket.general.PageWithHeaderAndFooter$11
> required-type   :
> com.vodecc.voipmng.boundary.wicket.general.PageWithHeaderAndFooter$11
> converter-type  :
> com.thoughtworks.xstream.converters.reflection.ReflectionConverter
> path:
> 
/com.vodecc.voipmng.boundary.wicket.trunkmonitor.TrunkMonitorPage/children/com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$1/children/com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$1$1[2]/children/com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$SubMenuList/children/children/org.apache.wicket.markup.html.list.ListItem/children/children/com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$NestedListEntry$1/children/org.apache.wicket.markup.html.list.ListItem[3]/children/children/val$visibilityFunction
> line number : 1
> class[1]:
> com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$SimpleListEntry
> class[2]: org.apache.wicket.markup.html.list.ListItem
> class[3]: [Ljava.lang.Object;
> converter-type[1]   :
> com.thoughtworks.xstream.converters.collections.ArrayConverter
> class[4]:
> com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$NestedListEntry$1
> class[5]:
> com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$NestedListEntry
> class[6]:
> com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$SubMenuList$1
> class[7]:
> com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$SubMenuList
> class[8]:
> com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$1$1
> class[9]:
> com.vodecc.voipmng.boundary.wicket.general.PageWithMenu$1

[xstream-user] Re: Re: XStream Json / OSGi application with jdk 1.4

2014-12-10 Thread Jörg Schaible
Hello Brice,

Brice Vandeputte wrote:
> 2014-12-10 11:27 GMT+01:00 Brice
>>
>>
>> I check "java.util.regex.Pattern" which is available since 1.4...
>> but this class seems not available on J9 JVM.

My J9 has no problems with it:


[INFO] BUILD SUCCESSFUL
[INFO] 

[INFO] Total time: 16 seconds
[INFO] Finished at: Wed Dec 10 23:26:37 CET 2014
[INFO] Final Memory: 38M/100M
[INFO] 

: ~/src/Codehaus/xstream-1.4.x/xstream $ java -version
java version "1.4.2"
Java(TM) 2 Runtime Environment, Standard Edition (build 2.3)
IBM J9 VM (build 2.3, J2RE 1.4.2 IBM J9 2.3 Linux amd64-64 
j9vmxa64142ifx-20110312 (JIT enabled)
J9VM - 20110202_74499_LHdSMr
JIT  - 20090210_1447ifx2_r8
GC   - 200902_24)


What kind of edition are you using?


>> I will maybe try to test an older version of xstream.
>
> Hey,
>   using xstream 1.4.2 I've no "regex.Pattern" usage in the main XStream
> classes
>   (only on some extended converters..)
>   So this works now !
>   (My need was only to be able to searialize in JSON a basic PoJo tree).
> 
>   A little question:
>   for "embedded users" like me (using J9 JVM); how could we make
> possible to continue to use the latest xstream version ?
>maybe add an xstream improvment to migrate native "regex
> Pattern" usage to a dedicated dependency like "jakarta-regexp"(available
> in
> osgi 1.4) ?  I don't know..

We can load the class dynamically. This happens already e.g. for the types 
in the java.sql.* package that are also not available in some embedded envs.

Just open a JIRA issue (you have to create a full user account at 
xircles.codehaus.org first).

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: XStream Json / OSGi application with jdk 1.4

2014-12-09 Thread Jörg Schaible
Hello Brice,

Brice Vandeputte wrote:

> Hi all,
> 
>  I'm trying to use XStream (JSON mode) with the following constraints:
> 
>   - jdk 1.4,
>   - Prosyst OSGi container.
> 
> 
> In the official "news.html" page, I read (nov 2011):
>>  Anyone who needs a version for Java 1.4.2 can build it easily from
> source, this build is still supported and part of CI.
> 
> So I get the xstream source and I compile it using JDK 1.4.2_19 and maven
> 2.0.11 (with success).
> In my target bundle application I just inline the following ressources
> from the distribution :
>  - xstream-1.4.7.jar
>  - jettison-1.0.1.jar
>  - stax-1.2.0.jar
>  - stax-api-1.0.1.jar
> 
> When I start my application, I Got the following result :
>  > org.osgi.framework.BundleException: Can't Resolve poc-bundle :
> com.ibm.xml.xlxp.api.stax
> 
> So my questions are:
> - is xstream always compliant with jdk 1.4 ?

Yes, otherwise you would not have been able to build it. The unit tests are 
quite extensive. OSGi support is a different story though.

> - do you know how to solve this dependency error ?
> - what's wrong in the way I use xstream ?

The reported error message indicates that this is an error reported by OSGi. 
My OSGi knowledge is very limited, therefore I'd check the manifests of the 
jars from above for this bundle requirement. Note, that no OSGi entries are 
added to XStream's manifest if you build with Java 1.4 (mainly because the 
Felix bundle-plugin requires a Java 5 runtime), you will have to handcraft a 
manifest on your own.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: specifying the comparator for TreeSetConverter

2014-11-27 Thread Jörg Schaible
Hi Amit,

sorry for the late response.

Amit Basu wrote:

> I get com.thoughtworks.xstream.mapper.CannotResolveClassException:
> comparator in
> 
com.thoughtworks.xstream.converters.collections.TreeSetConverter.unmarshal(TreeSetConverter.java:86)
> I am using a SortedSet with TreeSet impl and hibernate mapping file has
>  me, it seems XStream's TreeSetConverter is not getting my comparator class
> from the hbm.xml, and complaints that "comparator" class is not there. If
> I switch to Set and HashSet, there is no issue, but then I'd have to
> implement the sorting at a higher layer.

I am not sure what you try to accomplish. Any Hibernate support in XStream 
is one-way only i.e. you can marshal a Hibernate PersistentSortedSet and you 
will get a TreeSet at unmarshalling time.

Note, that I have absolutely no Hibernate experience, so I don't know what 
you can do with the Hibernate mapping files. All test code in Xstream was 
provided by helpful users.

As far as XStream is concerned, the PersistentSortedSet is handled by the 
HibernateSortedSetConverter which is derived from the TreeSetConverter. That 
one will marshal also the comparator that is returned by 
SortedSet.comparator().

So how does the XML for this comparator looks like that has been produced by 
XStream? What do you exactly mean with "complaints"?

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: ISO8601DateConverter without milliseconds

2014-11-19 Thread Jörg Schaible
Hi Brian,

Brian C. Huffman wrote:

> All,
> 
> Is there any way to use the ISO8601DateConverter without milliseconds?
> Right now, whenever I call xstream.toXML(object), I'm getting
> milliseconds in the output.
> 
> This is how I'm specifying the converter:
>  static {
>  xstream.registerConverter(new ISO8601DateConverter());
>  }

XStream's converter will always convert into a String with maximal 
information, but you can easily overwrite the toString method using a 
different formatter of Joda-Time:

  xstream.registerConverter(new ISO8601DateConverter() {
String toString(Object o) {
  return new DateTime(o).toString(ISODateTimeFormat.dateTimeNoMillis());
}
  });

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: xstream issue report

2014-11-17 Thread Jörg Schaible
Hi Andrey,

Andrey Rahimov wrote:

> Thank you for your help and deep response!
> 
> We found the problem it was our object model every object in our model has
> 
> @XStreamAlias("response")
> 
> for example
> 
> @XStreamAlias("response")
> public class AGPSRoutePoint extends ARoutePoint
> 
> So now if I changing this to different names in unit-tests like
> @XstreamAllia("ping"), @XstreamAlias("geo") it working well.
> 
> We have old backend and big base of Android/iOS users with old won't
> updated versions. The question is what approach you recommend us to use 
> to parse such xml?(Annotations will be most convenient way for us coz we
> have around 50 model classes with additional logic)

Your objects seemed to have a common parent (or implement a common 
interface) TypedInput. In this case you might define now an alias "response" 
for TypedInput and an own converter handling such a general TypedInput.

You will now have to tell this converter what type it actually should 
convert. You can "talk" to it using a DataHolder (it's a very simple map). 
Instead of

  fromXML = xstream.fromXML(bodyString);

You should invoke XStream with something like:

  DataHolder dataHolder = xstream.newDataHolder();
  dataHolder.put(Converter.class, this.getClass());
  InputStream in = new ByteArrayInputStream(bodyString.getBytes("utf-8"));
  fromXML = xstream.unmarshal(driver.createReader(in), null, dataHolder);

"driver" is an instance, you may keep along to the XStream:

  Driver driver = new XppDriver(); // XStream default
  XStream xstream = new XStream(driver);

The generic TypedInput converter should look like:

  class TypedInputConverter implements Converter {
ConverterLookup lookup;
TypedInputConverter(ConverterLookup lookup) {
  this.lookup = lookup;
}
boolean canConvert(Class type) {
  return type == TypedInput.class;
}
void marshal(Object source, HierarchicalStreamWriter writer, 
MarshallingContext context) {
  throw ConverterException("Marshalling unsupported");
}
Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext 
context) {
  Class realType = context.get(Converter.class);
  Converter converter = lookup.lookupConverterFor(realType);
  return converter.unmarshal(reader, context);
}
  }


This converter must have been registered:


  xstream.registerConverter(new 
TypedInputConverter(xstream.getConverterLookup()));


This approach assumes that you no longer use the "response" alias for 
something else and that you do not (un)marshal direct instances of 
TypedInput. Otherwise you must give more information to your class 
hierarchy.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: xstream issue report

2014-11-11 Thread Jörg Schaible
Hi Andrey,

Andrey Rahimov wrote:

> Hello!
> 
> I found very weird and annoying behavior in xstream(1.4.7 and tried 1.4.5)
> library on Android.
> 
> Basically ClassCastException if not recreate XStream object whenever
> deserialize new type of annotated object.
> 
> More details here:
> http://stackoverflow.com/questions/26778983/xstream-classcastexception-if-not-recreate-xstream-object-whenever-deserialize-n
> 
> Is here any possibility to avoid recreating xStream object every time?

There's normally no need to create a new instance every time. Normally, you 
simply create the instance, set it up and use it then everywhere (even 
concurrently).

However, setting up the XStream is *not* thread-safe, i.e. if you use auto-
detection for annotations or call processAnnotations, you will better use an 
own instance for each thread. See also FAQ, Javadoc and the annotations 
tutorial:

- http://xstream.codehaus.org/faq.html#Scalability_Thread_safety
- 
http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/XStream.html#autodetectAnnotations(boolean)
- http://xstream.codehaus.org/annotations-tutorial.html#AutoDetect

> Also even recreating xStream I'm getting this error approx. 4 crashes on
> 3000 users.

You can get in trouble if you marshal/unmarshal system resources:

- http://xstream.codehaus.org/faq.html#Serialization_types

> Can be the problem in our model?

You call processAnnotations on-the-fly i.e. you change the setup of the 
XStream instance. Every XStream instance builds internal caches during the 
(un)marshalling process and - apart from the concurrency problem - you might 
get surprising results, e.g. if an alias has been defined twice or a 
converter instance is already used for a type, you can register something 
different as long as you want, it won't have any effect.

However, since you're creating a new XStream instance yourself, you should 
not be affected. But you realize that your code is not thread-safe also? You 
create a new XStream instance and keep it in a member. Then you use that 
member in processAnnotations again and later on in fromBody. If fromBoby is 
called concurrently, you actually have no clue about which XStream instance 
is used in which state at which time ... and your code silently assumes that 
every type you have handled with toBody will use an XStream instance that 
has marshalled the same type in fromBody already before in the same run.

BTW: Your processAnnotations method with the loop is superfluous, XStream 
did the same already.

> 
> Regards, Andrey Rahimov

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Change a HashMap to TreeMap -> don't specify a Comparator?

2014-10-08 Thread Jörg Schaible
Hi Jamie,

Spence, Jamie wrote:

> Hi There,
> 
> I was previously using xStream to deserialzise a HashMap,
> but I would like to change this to TreeMap to introduce
> ordering on the String key. Is there a way of overriding the TreeMap
> converter to keep the current structure of my XML files (I want the same
> serialised structure as a HashMap)?

XStream uses by default the  element, but just because it calls 
internally at initialization time:

 this.addDefaultImplementation(HashMap.class, Map.class);

So you can call this method a second time with TreeMap as default for a Map 
implementation.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Streaming (large) data

2014-10-02 Thread Jörg Schaible
Hi Martin,

Martin Renner wrote:

> Hi,
> 
> I have to export a database into a XML file. As the objects contain BLOBs,
> I implemented a Converter for BLOBs:
> 
>   public void marshal(Object source, HierarchicalStreamWriter writer,
>   MarshallingContext context) {
>   Blob blob = (Blob) source;
>   context.convertAnother(blob.getBytes(1, (int) blob.length()));
> 
> This will read the whole BLOB into a byte array and delegate to
> EncodedByteArrayConverter. But the BLOBs are much too large to fit into
> the heap. So I have to find a way to stream this data (base64 encoded)
> into the output file.
> 
> However, I can not find any method in HierarchicalStreamWriter which would
> allow to stream character data.
> 
> As I already posted this question on the wrong list (dev instead of user,
> sorry),

Did you only read the top of my answer or also the the bottom with my hints 
regarding setText() ... ;-) ?

> I got the hint to use Woodstox and its interface XMLStreamWriter2,
> which apparently would allow to stream data. But I have no idea, how I can
> get access to the underlying Woodstox writer inside of a Converter.
> 
> In the above method, I can call "writer.underlyingWriter()", which returns
> an instance of StaxWriter. But this StaxWriter does not give access to its
> XMLStreamWriter.
> 
> How is it possible to stream data from a Converter into the output?

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Disable attribute escapping

2014-09-25 Thread Jörg Schaible
Hi Perdo,

Pedro Santos wrote:

> Hello all,
> 
> I've been hitting my head on the wall because I want variables in my
> classes to be serialized as attributes. This I'm being able to do. The
> only problem is that some strings that express conditions (e.g. "i < 3")
> still get escaped even though it's not necessary.

Why do you think that attribute values should *not* be escaped? XStream uses 
by default either its own XML writer implementation or - in case of a StAX-
based driver - the StAX XMLOutputFactory. Even the latter escape attribute 
values.

> Is there any way to turn off this behavior in XStream?

No by default, but you may overwrite PrettyPrintWriter.writeAttributeValue

- Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: Problem with unmarshall data (com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException)

2014-09-25 Thread Jörg Schaible
Hi Petr,

Petr Adamec wrote:

> Hi Jörg,
> I found error in my code. Now I can skip fields which are new. It is ok.
> Can I write skipped fields into log file, if I use override wrapMapper?

sure, you can log in any play you want. :-)

- Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Problem with unmarshall data (com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException)

2014-09-20 Thread Jörg Schaible
Hi Petr,

Petr Adamec wrote:

> 
> Good morning,
> I have a problem with convert from xml to data (unmarshall) when I use
> xml which has unknown tags. Xstream write me Exception in thread "main"
> 
com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException:
> No such field.

This is the expected behavior.

> I was looking for solution for my problem on internet. I find some it
> but all of them do not working on my case.
> 
> I override method wrapMapper but it still no working.
> 
> XStream xstream = new XStream() {
> 
>  // to enable ignoring of unknown elements
> 
>  @Override
> 
>  protected MapperWrapper wrapMapper(MapperWrapper next) {
> 
>  return new MapperWrapper(next) {
> 
>  @Override
> 
>  public boolean shouldSerializeMember(Class definedIn,
>  String fieldName) {
> 
>  if (definedIn == Object.class) {
> 
>  try {
> 
>  return this.realClass(fieldName) != null;
> 
>  } catch (Exception e) {
> 
>  return false;
> 
>  }
> 
>  }
> 
>  return super.shouldSerializeMember(definedIn,
>  fieldName);
> 
>  }
> 
>  };
> 
>  }
> 
>  };
> 

Which version of XStream are you using? 
 
> Is it maybe because I have a collection at class. But every options
> which I try not works.
> 
> My class which I need convert to/from  is
> 
> public class Configurations implements Serializable{
> 
>  private static final long serialVersionUID = 4392719277296957995L;
> 
>  private List> tableNames;
> 
>  private Map, List>
>  tables;
> 
>  ...
> 
>  }
> 
> 
> Updatable is only interface. I need  convert to/from xml every class
> which implements this interface.
> 
> In normal case, when I has right xml (get from marshell data) it is ok.
> I can convert data to this xml and xml back to data.
> 
> 
> 
>
> 
>  mypackage.configuration.MyClass
> 
>
> 
>
> 
>  
> 
>mypackage.configuration.MyClass
> 
>
> 
>  
> 
>0
> 
>2014-09-19 08:49:34.649 UTC
> 
>true
> 
>  
> 
>
> 
>  
> 
>
> 
> 
> 
> 
> But when I change xml (forr example add new tag newTag)
> 
> 
> 
>
> 
>  mypackage.configuration.MyClass
> 
>
> 
>
> 
>  
> 
>mypackage.configuration.MyClass
> 
>
> 
>  
> 
>0
> 
>2014-09-19 08:49:34.649 UTC
> 
>true
> 
>exam
> 
>  
> 
>
> 
>  
> 
>
> 
> 
> 
> 
> Xstream ends with error
> AbstractReflectionConverter$UnknownFieldException: No such field. Is
> exists solution how can I solve this problem? I need convert to data
> (class) and if xml has unknown tags which does not exist at class, logg
> some message and skip tag.

See http://xstream.codehaus.org/faq.html#Serialization_newer_class_versions

The topics also direct you to the proper location of the custom mapper from 
above.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: XStream Worked Great

2014-09-17 Thread Jörg Schaible
Hi Raj,

Raj wrote:

> Hi
> 
> I used Xstream in my current project and it worked pretty well. My
> scenario was that i have complete running app and suddenly requirement
> came to convert objects to xml in particular schema. I used annotations
> and custom converter. The custom converters gives all the flexibility for
> creating xmls.
> 
> Till Now, No issues.

Thanks for the feedback :)

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Xstream difference in behaviour between android 4.1 and 4.3

2014-09-17 Thread Jörg Schaible
Hi Charles,

sorry for the delay, working on the backlog ...

Charles Colbourn wrote:

> 
> Hi
> 
> I've stumbled over a bit of an oddity with Xstream across these two
> versions of Android.

actually I have no Android, so I can only assume ...

> If you have an annotated field:
> 
> @XStreamImplicit
> public ArrayList myMessages = new ArrayList();
> 
> and you read XML using Xstream.fromXML(string);
> 
> and test to see if your field has been populated:
> 
> if ( myMessages.size()>0 ) {#dostuff
> 
> 
> On 4.1 it will work, but 4.3 it will barf with an NPE. In other words,
> when reading the XML on 4.1 it seems to leave any fields alone that are
> not represented in the XML, whereas on 4.3 it seems to assign null to
> them.
> 
> I've got around the problem by
> 
> if ( myMessages != null && myMessages.size()>0 )
> 
> but I'd have expected it to be consistent.

It looks like XStream does not run in enhanced mode on the older Android 
version (requires stuff from sun.misc.Unsafe). In that case it cannot 
instantiate objects without running the initializers. If your implicit list 
contains no element, XStream does not know about the list member at all at 
deserialization time and leaves it alone. So the list instance must have 
been created by the Java initializers of the class.

Which version of XStream are you using? Do you have some kind of console 
where you can run com.thoughtworks.xstream.core.JVM and compare the output?

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: fromXML exception on the client when a new field is added to the incoming object/xml

2014-09-17 Thread Jörg Schaible
Hi Hari,

sorry for the late response, but I was on holidays and work through the 
backlog now.

Kilakkencherry, Hariharan G wrote:

> Hi,
> 
> I have a client which is using an old interface and the provider has added
> a new field to the class. So when I am trying to deserialize the incoming
> object using the method fromXML I get an exception.

This is the intended behavior.

> What can be done on
> the client side to work around this issue without having to update the
> interface to match with the server every time there is a change?

See http://xstream.codehaus.org/faq.html#Serialization_newer_class_versions
As an additional alternative you can setup XStream to omit the field for the 
class (even if the class does not have the member at all).

Cheers,
Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Problem using the NamedMapconverter

2014-09-17 Thread Jörg Schaible
Hi Johann,

sorry for the late response, but I was on holidays and try to clear the 
backlog slowly again.

Johann Kerdal wrote:

> Hi guys,
> 
> I need to unmarshall an XML document to a
> linkedHashMap
> 
> The XML document I get from the server system is containing the list of
> objects:
> 
>   BSI_REFIN_INTR_BU_CURRY_AMT
>   Refinancing interest amount in BU currency
>   8.0
>   NLNUM18.
>   NLNUM18.
>   
> 
> As you can see, the key is an attribute of the ColumnAttributes Element.
> 
> I have tested this code:
> new NamedMapConverter(LinkedHashMap.class,xstream.getMapper(),
> "column", "key", String.class, *"column"*, ColumnAttributes.class, true,
> false, xstream.getConverterLookup())
> 
> but it generates one element for the key and one for the value.
> 
> If I use this one:
> new NamedMapConverter(LinkedHashMap.class,xstream.getMapper(),
> "column", "key", String.class, *null*, ColumnAttributes.class, true,
> false, xstream.getConverterLookup())
> 
> Here is the complete code:
> XStream xstream = new XStream(new DomDriver());
> // XStream xstream = new XStream(new DomDriver());
> xstream.alias("columns",LinkedHashMap.class) ;
> xstream.alias("column",ColumnAttributes.class) ;
> ConverterLookup lookup = xstream.getConverterLookup() ;
> Converter conv =
> xstream.getConverterLookup().lookupConverterForType(String.class) ;
> System.out.println(conv.canConvert(String.class)) ;
> xstream.registerConverter(
>  new NamedMapConverter(LinkedHashMap.class,xstream.getMapper(),
> "column", "key", String.class, null, ColumnAttributes.class, true, false,
> xstream.getConverterLookup()
> ));
> // String xml = xstream.toXML(rulesBook.getColumnsAttributes());
> // System.out.println(xml);
> String xml=" 
key=\"BSI_REFIN_INTR_BU_CURRY_AMT\">BSI_REFIN_INTR_BU_CURRY_AMTRefinancing
> interest amount in BU
> currency8.0" ;
> LinkedHashMap test =
> (LinkedHashMap)xstream.fromXML(xml) ;
> 

[snip]

> 
> 
> Is it possible to have the key as an attribute of the value element in the
> XML using the NamedMapconverter?

No. See, a map has normally following XML representation:

 
  
K
V
  
 

where K and/or V might either be a String or another XML structure. The 
NamedMapConverter allows you to use different names for the inner elements 
entry, key and value.

A special mode is offered to drop the entry element:

 
  K
  V
 

Or you might use attributes for key and/or value *if* K resp. V is a String 
i.e. the converter for those objects returns a single value. However, then 
you have to keep the entry element:

 
  
V
  
 

or:

 
  
 

Nevertheless, the representation for key and value is always present either 
as XML element or attribute.

Since your value type contains the key, you try to drop the key element of 
the map and use the value as entry element instead with an attribute for the 
key property. Obviously your situation does not match the functionality of 
this converter.

> If not, do you have any suggestion for me?
> 
> Any feedback is welcome..

I would actually just use a custom converter for the LinkedHashMap (register 
locally if the LinkedHashMap is an element of a higher level, otherwise all 
LinkedHashMaps will be handled):

== %< ===
 class AttributesConverter implements Converter {
   Converter listConverter;
   AttributesConverter(Mapper mapper) {
 listConverter = new CollectionConverter(mapper);
   }
   boolean canConvert(Class t) {
 return LinkedHashMap.class.equals(t);
   }
   void marshal(Object source, HierarchicalStreamWriter writer, 
MarshallingContext context) {
 Map map = (Map)source;
 listConverter.marshal(map.values(), writer, context);
   }
   Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext 
context) {
 Collection values =
   listConverter.unmarshal(reader, context);
 Map map = new LinkedHashMap<>();
 for(ColumnAttributes attr : values) {
   map.put(attr.getKey(), attr);
 }
 return map;
   }
 }
 xstream.registerConverter(
   new AttributesConverter(xstream.getMapper()));
 xstream.useAttributeFor(ColumnAttributes.class, "key");
 xstream.alias("ColumnAttributes", ColumnAttributes.class);
== %< ===

Hope this helps,
Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: About XStream mode accuracy in javadoc and performances

2014-09-15 Thread Jörg Schaible
Hi Philippe

Philippe Mouawad wrote:

> Hello,
> I was wondering if the Javadoc of XStream regarding mode was still
> accurate regarding mode
> 
>-
>
http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/XStream.html
> 
> 
> xstream.setMode(XStream.NO_REFERENCES); This disables object graph support
> and treats the object structure like a tree. Duplicate references are
> treated as two separate objects and circular references cause an
> exception. This is slightly faster and uses less memory than the other two
> modes.
> 
> 
> What seems strange is :
> 
> 
> *This is slightly faster and uses less memory than the other two modes.*

Originally we had only 3 modes: ID, XPATH and no references at all. Then we 
introduced relative and absolute XPATHs and some time later the single 
reference modes for the two XAPTH variants. Seems not all documentation is 
up-to-date ...

> It mentions 2 modes while javadoc shows 5 modes, is it really faster and
> uses less memory or the new modes are better.

The comments for NO_REFERENCES still applies. XStream does then not have to 
keep track of the unmarshalled objects just because they might be referenced 
somewhere later on.

> I am concerned about the issues related to NO_REFERENCES mode as per:
> http://xstream.10960.n7.nabble.com/Hints-for-Tracking-down-a-CircularReferenceException-td4531.html

If your object graph contains no circles, you cannot get this exception ;-)
Otherwise you would end up in an endless loop.

> Thanks for help, and by the way GREAT PROJECT !

Thanks for the feedback,
Jörg 



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: xstream multi thread issue.

2014-08-13 Thread Jörg Schaible
Hi Ming,

Huang, Ming wrote:

> Hi
> 
> We recently updated xstream from from version 1.3.1 to 1.4.7 in our
> application. We found that the application would sometimes hang. Doing
> jstack and found that the threads were in the lines of at
> 
com.thoughtworks.xstream.core.util.PrioritizedList.iterator(PrioritizedList.java:44).
> Attached is the full stack.  Can someone help me on this? Do I need to put
> synchronized around XStream.toXML() call?

Normally no, XStream is thread-safe for concurrent 
marshalling/unmarshalling. Unless you process annotations on-the-fly, 
XStream documentation contains a lot of warnings about it:

http://xstream.codehaus.org/faq.html#Scalability_Thread_safety
http://xstream.codehaus.org/annotations-tutorial.html#AutoDetect
http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/XStream.html
http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/XStream.html#autodetectAnnotations(boolean)

So, how do you setup your XStream instance? Which Java VM you are using?

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: Implicit Collection where collection is a generic type

2014-08-11 Thread Jörg Schaible
Hi Gabriel,

Gabriel Rossetti wrote:

> Hi Jörg,
> 
> ok, I tried but I need to request access to the JIRA, is that you that has
> to give me access?

You have to create a full account at xircles.codehaus.org that will be used 
also as JIRA account. XStream is just using Codehaus resources, we have no 
further administrative rights.

Cheers,
Jörg

> 
> Thanks,
> Gabriel
> 
> 
> On Mon, Jun 30, 2014 at 6:57 PM, Jörg Schaible
>  wrote:
> 
>> Hi Gabriel,
>>
>> Gabriel Rossetti wrote:
>>
>> > Hi all,
>> >
>> > I have an issue un-serializing a class with a generic type. Here is an
>> > example:
>> >
>> > public abstract class Message {
>> >
>> >   protected T data;
>> >   // getters and setters
>> > }
>> >
>> > public class StringListMessage extends Message  > {
>> >
>> >   protected T data;
>> >   // getters and setters
>> > }
>> >
>> > For example. I am using addImplicitCollection like this:
>> >
>> > xstream.addImplicitCollection(StringListMessage.class, "data");
>> >
>> > get the following error:
>> >
>> > Field "data" declares no collection or array
>> >
>> > I can't find anything online about this.
>>
>> the case is simply not supported. However, IIRC it is possible to get the
>> bounded type at runtime (currently it simply detects "Object"). Please
>> open a JIRA issue.
>>
>> Cheers,
>> Jörg
>>
>>
>> -
>> To unsubscribe from this list, please visit:
>>
>> http://xircles.codehaus.org/manage_email
>>
>>
>>



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Android XSTREAM W/dalvikvm no implementation found for native Ldalvik/system/VMRuntime;.pauseGc:(Ljava/lang/String; )I on Samsung device]

2014-08-09 Thread Jörg Schaible
Hi Jean-Marc,

gempe...@xs4all.nl wrote:

> Hi All,
> 
> I'm using XSTREAM for Android and since Samsung updated the NOTE 2 to
> 4.4.2 I have this error
> "Android XSTREAM W/dalvikvm no implementation found for native
> Ldalvik/system/VMRuntime;.pauseGc:(Ljava/lang/String;)I on Samsung device"
> 
> This also happen with last GALAXY S 10.1 T-800 !
> 
> I don't have the issue on CUSTOM ROM such as OMEGA GS4 and on an OLD
> Galaxy S ROM with Cyanogenmod 11...
> 
> Surely this is not an XSTREAM issue but probably a bug from Samsung on
> there latest ROM it seems from what I read on google which also redirected
> other people with same issue to Samsung...but nothing seems to happen on
> this front.
> 
> The issue happen when I call XSTREAM toXML() to serialize, there is no
> problem at all to de-serialize.
> 
> Basically I'm desperate for some kind of workaround... I looked at
> building XSTREAM for Android to see if I can figure out something
> debugging but failed... I did no really find easy pointer ( I might
> overlook things, sorry if this is the case) on how to build it using
> Eclipse.
> 
> Any pointer, suggestion would be great.
> 
> Many thanks for your great library

Which version of XStream are you using? I have no idea why there should be a 
reference to dalvik.system.VMRuntime, XStream uses no such reference. 
XStream tries to identify the supported functionality in c.t.x.core.JVM, 
this included specific behavior for Dalvik. So, if we can identify what 
triggers your reported error, we might be able to do something.

For development you can simply checkout the source. XStream is Maven-based. 
Call

  mvn eclipse:eclipse

from the project root to generate the Eclipse projects.

However, personally I do no Android development, so any Android support in 
XStream is based on user reports.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Calling context.convertAnother vs directly calling marshal/unmarshal

2014-07-29 Thread Jörg Schaible
Hi Gabriel,

Gabriel Rossetti wrote:

> Hi all,
> 
> I have custom converters which call other converters, currently I call
> context.convertAnother() but this takes time since it cycles through the
> converters and calls canConvert()

Only once, the selection is cached.

> (even though I gave it the converter
> instance).

Normally you don't provide an own converter, but if you do, XStream checks 
its usability.

> Anyways, what is the advantage to use this method vs directly
> calling the marshal/unmarshal on the converter instance? I don't really
> see the advantage in this case since I know which converter to use, am I
> missing something?

References to/from such elements will not work. No detection of endless 
recursion in case of a cycle in an object graph. No reuse of existing 
converter instance for elements of same type elsewhere (some converter 
implementations build up own caches).

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Using XStream with class hierarchy in Java 8 gives incorrect results

2014-07-17 Thread Jörg Schaible
Hi Lesley,

Lesley Perkins wrote:

> Hello.  I'm running into an issue with XStream starting with Java 8.  This
> works correctly in Java 7.  Take the following example:
> 
> import java.io.*;
> 
> import com.thoughtworks.xstream.XStream;
> import com.thoughtworks.xstream.io.xml.DomDriver;
> 
> public class XStreamJre8
> {
> 
>public static void main(String[] args)
>{
>   Child child = new Child(2, 3);
> 
>   try
>   {
>  String fileName = new StringBuilder()
>   .append("child_")
>   .append(System.getProperty("java.version", "unknown"))
>   .append(".xml")
>   .toString();
>  FileOutputStream out = new FileOutputStream(new File(fileName));
>  XStream xStream = new XStream(new DomDriver());
>  xStream.toXML(child, out);
>  out.close();
>   }
>   catch (Exception e)
>   {
>  e.printStackTrace();
>   }
>}
> 
>static class Parent
>{
>   private int parentVar;
> 
>   public Parent ()
>   {
>  this(-1);
>   }
> 
>   public Parent(int parentVar)
>   {
>  this.parentVar = parentVar;
>   }
> 
>   public int getParentVar()
>   {
>  return parentVar;
>   }
>} // end class Parent
> 
>static class Child extends Parent
>{
>   private int childVar;
> 
>   public Child()
>   {
>  this(-1, -1);
>   }
> 
>   public Child(int parentVar, int childVar)
>   {
>  super(parentVar);
>  this.childVar = childVar;
>   }
> 
>   public int getChildVar()
>   {
>  return childVar;
>   }
>} // end class Child
> 
> }
> 
> When I execute this with Java 7u51, my output is:
> 
> 
>   2
>   3
> 
> 
> However, when I execute with Java 8u or 8u11, my output is:
> 
> 
>   3
> 
> 
> You can see that the parent class is being ignored.  I'm not sure what
> changed that would cause this, but it's definitely an issue for me.  Any
> help/solutions would be appreciated.

A lot of unit test would break in XStream if there is a general problem of 
this sort with Java 8, but the test suite runs perfectly with current Java 8 
versions (https://bamboo-ci.codehaus.org/browse/XSTREAM).

So, which version of XStream are you're using?

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Unexpected parsing error in CDATA block

2014-07-16 Thread Jörg Schaible
Hi Sebastian,

Sebastien Degardin wrote:

> I'm parsing an xml which contains a CDATA block and I get the following
> exception:
> 
> "Caused by: org.xmlpull.v1.XmlPullParserException: start tag unexpected
> character @ (position: TEXT seen ...mailto:Mll@dk]>   @9:100)
>  at org.xmlpull.mxp1.MXParser.parseStartTag(MXParser.java:1803)
> at org.xmlpull.mxp1.MXParser.nextImpl(MXParser.java:1127)
>  at org.xmlpull.mxp1.MXParser.next(MXParser.java:1093)"
> 
> for this:
> 
> ""
> 
> If I remove the first occurrence of double brackets if does work. it seems
> to me that xstream identify double brackets "]]" as the end of the CDATA
> block instead of "]]>"
> 
> I'm using Java 6 and xstream 1.4.2

unfortunately there's nothing XStream can do. This is a (known) error in the 
Xpp3 parser and it seems that Xpp3 development is completely dead, I don't 
even know where I should report it.

You will have to use a different parser engine (e.g kXML2 using the 
KXml2Driver).

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Duplicate Class Names/Aliases

2014-07-15 Thread Jörg Schaible
Hi Ken,

Ken Goudey wrote:

> I am working with Spring 3.2 and xstream to marshall/unmarshall XML and
> have been running in circles trying to unmarshall annotated classes with
> the same name/alias.


First let me say, that I don't know Spring and what Spring actually does 
with XStream.

Aliasing can be done for classes and fields (see 
http://xstream.codehaus.org/alias-tutorial.html). These two types are 
completely separate, they will not interfere each other.

Multiple alias definitions will clobber each other, if they are not unique:

== %< =
xstream.alias("text", String.class);
xstream.alias("text", StringBuilder.class);
assertEquals("Hello", xstream.toXML("Hello"));
assertEquals("Hello",
  xstream.toXML(new StringBuilder("Hello")));
assertEquals(new StringBuilder("Hello"),
  xstream.fromXML("Hello"));
== %< =

As you can see, the definition sequence is essential.


> The gist of it is that I want two separate packages
> to contain similar models, with a spring configuration like this:
> 
>  class="org.springframework.oxm.xstream.XStreamMarshaller">
> 
> 
> com.watchwith.Show
> com.watchwith.Content
> com.watchwith.alternate.Show
> com.watchwith.alternate.Content
> 
> 
> 


The definition sequence is not obvious using annotations though. All I can 
assume from this XML snippet is, that Spring will call 
xstream.processAnnotations(Class[] types) internally. However, let's assume 
you have following classes and call then XStream to process those classes' 
annotations:

== %< =
class A {
 C c;
}
@XStreamAlias("same")
class B {
}
@XStreamAlias("same")
class C {
}
xstream.processAnnotations(A.class, B.class, C.class);
== %< =

XStream will process A, B and C in this sequence, i.e. it would normally 
register any annotated alias for A, then for B and in the end for C. 
However, in this case A contains a member of type C. Therefore XStream will 
actually process these classes in the sequence A, C, B. As documented above, 
this will have an effect here. While B and C will marshal both to an XML 
element with name "same", the unmarshalling will always produce an element 
of type B.


> In either "Show" and "Content" class I have the same aliases annotated:
> 
> @XStreamAlias("show")
> public class Show {


The following field alias is superfluous, since the field is already named 
"content".


> @XStreamAlias("content")
> private Content content;
> ...
> }


The following class alias does not interfere with the field alias above.

 
> @XStreamAlias("content")
> public class Content {...}
> 
> And in my @Controllers I am importing the correct object, however, it
> seems that xstream chooses one of the packages/aliases (possibly
> alphabetically?) and always tries to unmarshall to that model. Is there a
> way (short of distinct aliases) to advise xstream to which class the
> incoming XML should be unmarshalled, since it does not appear to honor the
> value of the @RequestBody annotation?


Sorry, I don't know about @Controllers or @RequestBody.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: xStream changes order of objects in write/readObject with JSON serialization

2014-07-04 Thread Jörg Schaible
Hi Anatoly,

Анатолий Инсапов wrote:

> Hello, Jörg
> 
> Thank You.
> I understand limitation of JSON itself.But while list often contains
> objects of same type and order is not always issue, order of
> read/writeObject is important.
> I tried jettison 1.2 and 1.0.1 but result was the same. For now we just
> removed our code which cause us problem during deserialization. If some
> legacy code will appear suppose we just use hotfix.

what you always may try is to use a different converter e.g. sometimes it is 
possible to use the ReflectionConverter or a JavaBeanConverter instead. It 
depends on the serialized object.

However, if I understand correctly, you already deal with JSON that has been 
serialized by a former version. The proposed solution only helps if you 
supervise serialization already.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: xStream changes order of objects in write/readObject with JSON serialization

2014-07-03 Thread Jörg Schaible
Hi Anatoly,

Анатолий Инсапов wrote:

> Hello.
> 
> My problem and reseach described there
> http://stackoverflow.com/questions/24449238/xstream-changes-order-of-objects-in-write-readobject-with-json-serialization

This is a behavior of Jettison's heuristics transforming XML into JSON. It 
will collect values from sibling elements with same name and form an array. 
Which version of Jettison are you using? Note, that only Jettison 1.2 pass 
XStream's unit tests, the complete 1.3.x series is borked.

> I suppose it is easer to read formatted text with syntax highlighting but
> I can copy content into mail if needed. I attach link to simplest patch in
> comments - http://pastebin.com/n3qpRGHS .
> 
> We use xStream 1.4.7. Is there way to fix it in 1.4.7(or 1.4.8)?

Sorry, but there's not much we can do about it, the JSON heuristics has its 
limits. See, you will get the same problem with this list:

List list = new ArrayList<>();
list.add("First");
list.add(Integer.valueOf(2));
list.add("3rd");
list.add(Long.valueOf(4));

Therefore any element sequence with arbitrary types is affected. This 
includes stuff explicitly written in writeObject() as well as Exernalizable 
instances, and so on...

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Mapping JSON to XML without Java Objects

2014-07-03 Thread Jörg Schaible
Hi Lewis,

Lewis John Mcgibbney wrote:

> Hi Folks,
> I work on an object-to-datastore mapping framework called Apache Gora [0]
> and recently came across XStream for simplying data modeling in Gora.
> 
> I really like the project you guys are working on but i wonder if you can
> answer me one question.
> 
> Can I use only JSON e.g. as a string or FileInputStream as oppose to
> having to pass around objects? e.g. xstream.alias("product",
> Product.class);
> 
> Say for example I have many Objects, or another example would be that I do
> not actually have objects but I have JSON which "represents" the
> object(s).

XStream's HierarchicalStreamDriver is simply a vehicle to provide 
HierarchicalStreamReader and HierarchicalStreamWriter instances 
reading/writing the same format (encapsulating additionally underlaying 
implementations for parsers and formatters).

Technically it is no problem to use those implementations independently. 
Since XStream's hierarchical stream has a unified model, it *is* possible to 
transform the stream from one format into the other:

 %< ==
HierarchicalStreamReader reader =
  new JettisonMappedXmlDriver().createReader(inputStream);
HierarchicalStreamWriter writer = new PrettyPrintWriter(javaIoWriter);
new HierarchicalStreamCopier().copy(reader, writer);
 %< ==

> In Gora we do data modeling in JSON before we compile the JSON into data
> beans therefore it would be much easier if I were able to produce XML from
> JSON as oppose to assuming that Java objects will be available.

While you can do so with XStream, you should be aware, that XStream uses 
Jettison as JSON parser, which is a wrapper around StAX translating the JSON 
into the StAX model. Therefore you might get away here without the overhead 
of XStream using the MappedXMLInputFactory of Jettison directly, which is an 
implementation of StAX' XMLInputFactory.

Note, that newer Jettison version break XStream, because of a strange array 
handling, you'll need version 1.2 (I have not tried latest version 1.3.3 
yet).

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Implicit Collection where collection is a generic type

2014-06-30 Thread Jörg Schaible
Hi Gabriel,

Gabriel Rossetti wrote:

> Hi all,
> 
> I have an issue un-serializing a class with a generic type. Here is an
> example:
> 
> public abstract class Message {
> 
>   protected T data;
>   // getters and setters
> }
> 
> public class StringListMessage extends Message  > {
> 
>   protected T data;
>   // getters and setters
> }
> 
> For example. I am using addImplicitCollection like this:
> 
> xstream.addImplicitCollection(StringListMessage.class, "data");
> 
> get the following error:
> 
> Field "data" declares no collection or array
> 
> I can't find anything online about this.

the case is simply not supported. However, IIRC it is possible to get the 
bounded type at runtime (currently it simply detects "Object"). Please open 
a JIRA issue.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: sorting xml

2014-06-06 Thread Jörg Schaible
Hi,

js wrote:

> trying to create CodeType and child Code classes from this xml with Codes
> in alphabetical order based upon 

You can't. That's not what a FieldKeySorter is for. Such an implementation 
defines the sequence of the fields (incl. inherited) of a specific type i.e. 
you can "sort" "codeValue" and "description" for the members of Code.class. 
However, a SortableFieldKeySorter requires the defined sequence for *all* 
fields of the type, otherwise it complains with a StreamException.

> 
> 
>AddressType
> 
>  -
> 

> 
>  -
> 

>  
>  B
>  Business
>  
> 
>  -
> 

>  
>  CON
>  Confidential Address
>   
> 
> 
> 
> 
> 
> CodeType codeType = new CodeType();
> XStream xstream = new XStream(new StaxDriver());
> SortableFieldKeySorter sorter = new SortableFieldKeySorter();
> sorter.registerFieldOrder(Code.class, new String[] { "codeValue"
> }); xstream = new XStream(new PureJavaReflectionProvider(new
> FieldDictionary(sorter)));
> 
> try {
> xstream.alias("codeType", CodeType.class);
> xstream.alias("code", Code.class);
> codeType = (CodeType)xstream.fromXML(xml.getInputStream());
> }
> catch { ... }
> 
> jars:
> xstream-1.4.7.jar
> xpp3_min-1.1.4c.jar
> xmlpull-1.1.3.1.jar
> 
> if i comment out:
> xstream = new XStream(new PureJavaReflectionProvider(new
> FieldDictionary(sorter)));
> 
> it works.
> 
> otherwise, all is null in CodeType
> 
> whats the most basic way to enable sorting in Xstream?


Apart from the sequence of fields, XStream does not sort its output. You may 
apply a stylesheet to perform the sorting in a post-processing step:
http://xstream.codehaus.org/manual-tweaking-output.html#Procesing_XSLT

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: ActionScript3 port of XStream

2014-06-02 Thread Jörg Schaible
Hi,

kokori...@gmail.com wrote:

> Hello, XStream users!
> I ported XStream to AS3 and called that library AStream. You can see it
> here: https://github.com/kokorin/AStream
> 
> AStream currently supports:
>   - Primitive types (int, uint, Number, String, Boolean and null)
>   - Complex types
>   - Enums (based on as3.lang.Enum)
>   - Collections: Array, typed Vector and all collections from Flex
> (based on mx.collections.IList)
>   - Implicit collections (without separate parent tag)
>   - Classes implementing IExternalizable
>   - Aliases for class, property and package
>   - Different types of handling cycle- and cross-references in object
>   - Output customization with metadata and code
> 
> Does anyone interested in that port?
> Is there a chance that it would be mentioned on XStream site?

For sure, we can add a link on the references page in an own section for 
ports.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: Re: basic unmarshall question

2014-05-21 Thread Jörg Schaible
Hi John,

js wrote:

> Jörg, got it.. it works..thank you
> i guess i was just looking for that "aha" moment... which your feedback
> provided.


Glad to here.

 
> in the alias tutorial, even though it says "..make XStream read/write", it
> never really set in that it was anything other than a marshall example.
> An actual unmarshall method there (and in the other examples) would drive
> home your point that alias() and addImplicitCollection() is applicable to
> both serialize and deserialize.


For us developers it's natural that it works in both directions. Maybe this 
is our blind spot here. I'll try to improve the docs for the next release.


> your advice to first create the xml via xstream methods makes perfect
> sense now.
> i was able to find duplicate  elements (class name and collection
> name) and move forward quickly without the previous errors.


Development is efficient and much less frustrating that way. I know.

 
> again, thanks


You're welcome,
Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: basic unmarshall question

2014-05-20 Thread Jörg Schaible
Hi John,

js wrote:

> 
> Well, no. Not really. See, XStream is about Java object to XML *and back*,
> i.e. every example can also unmarshal.
> 
> Therefore adjust the marshalling. If XStream generates the required XML
> format, it can also read it. It is a very tedious and annoying task to try
> it the other way round (you already found this out), because you never
> know - especially as starter - why XStream throws an exception or silently
> skips some elements.
> 
> 
> 
> Typically, the use cases will be objects->xml for use by 3rd party or
> xml->objects where inbound xml was created by a 3rd party. Unless i was
> simply persisting and reading unmodified serialized data, i would expect
> that the inbound and outbound xml is different and created/digested by
> applications that may not even be java.


Your expectation does not have any influence, how XStream works.


> i created (marshalled/serialized) some test xml as follows:
> Persons ps = new Persons();
> Person p1 = new Person();
> p1.setName("joe");
>  s.getPersons().add(p1);
> Person p2 = new Person();
> p1.setName("blo");
> ps.getPersons().add(p2);
> System.out.println(xstream.toXML(ps));
>

> while i *try* to unmarshalled/deserialize as follows:
> XStream xstream = new XStream(new StaxDriver());
> stream.alias("persons", Persons.class);
> xstream.alias("person", Person.class);
> xstream.addImplicitCollection(Person.class, "person");
> etc.
> 
> These seems to be a very different set of methods.


??

Sorry, but I don't understand your comment. With those methods you influence 
the XML format that is written *and* read.

 %< ===
Persons ps = new Persons();
Person p1 = new Person();
p1.setName("joe");
s.getPersons().add(p1);
Person p2 = new Person();
p1.setName("blo");
ps.getPersons().add(p2);

XStream xstream = new XStream(new StaxDriver());
xstream.alias("persons", Persons.class);
xstream.alias("person", Person.class);
// next is useless, Person.class has no member person
xstream.addImplicitCollection(Person.class, "person");

String xml = xstream.toXML(ps);
System.out.println(xml);
assertEquals(ps, xtream.fromXML(xml));
 %< ===

Will work (proper equals() implementations implied). It simply does not yet 
write XML in the format you'd like to read in the end.

> My problem is that i
> can't find adequate examples (or documentation) on how to use alias() and
> addImplicitCollection() methods when unmarshalling collections.

Again, there's no difference between marshalling and unmarshalling. The 
question is, which part of the tutorial do you not understand?

http://xstream.codehaus.org/alias-tutorial.html

- Jörg

> 
> 
> ---
> 
> 
> Why do you think the objects have to be POJOs?
> 
> 
> 
> My xml needs to get deserialized into objects and then those objects used
> by the application. Why not unmarshall directly into my existing POJOs
> instead of having to create a whole new set of "command" (abstraction)
> classes whose only difference is that their accessors/mutators are get(),
> add() instead of the POJO standard get(), set()?


XStream does not call any of the methods.


> Things are much cleaner if i can (un)marshall using a simple library and
> leave my domain unmodified (which is why i'm trying to avoid xstream
> annotations).


Personally, I don't use annotations either - for exactly the same reason. 
However, why do you think you cannot read/write into your domain model? 
That's what I normally do with XStream. Procedure is the same again: Write 
your domain model objects as XML and then start to tweak the output.


> I questioned the requirement of get(), add() and collections as lists,
> because that is whats used in the examples and i thought maybe they were
> required.


The generic (reflection-based) converters will look for declared members 
only. No methods or constructors required.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: basic unmarshall question

2014-05-20 Thread Jörg Schaible
Hi John,

js wrote:

> hi,
> 
> I'll eventually figure this out, but i have been struggling for at least 2
> days trying to unmarshall the simplest xml.. i must really be getting
> frustrated if i resorted to emailing the open source developers.. anyway:
> 
> all i want to do is unmarshall a simple xml file involving nested
> collections
> 
> 
> billy
> 
> West St.
> 
> 
> East St.
> 
> 
> bob
> 
> North St.
> 
> 
> South St.
>  
> 
> 
> 
> 
> i have tried all the examples at codehaus (which are all
> marshall-centric).


Well, no. Not really. See, XStream is about Java object to XML *and back*, 
i.e. every example can also unmarshal.


> i have googled countless sites.
> no where have i found a simple, complete example that does this most basic
> of requirements.


Because it's not necessary? ... see below ;-) 

 
> if collections are created, they are either null or empty.
> Lots of: No field "person" for implicit collection errors as well.
> 
> == CODE =
> 
> public class Persons {
> 
> private List persons = new ArrayList();
> 
> public List getPersons() {
> return persons;
> }
> public void setPersons(List persons) {
> this.persons = persons;
> }
> 
> }
> //this is a "command" class as one does not need a model class for
> "persons" thus the List instead of Set (i was just following examples i
> found online, but would rather it be a set as well).


You may also use directly an array (Person[]).


> //also, why examples have get() and add(), instead of POJO get(), set()?


Why do you think the objects have to be POJOs?

 
> -
> 
> public class Person {
> 
> private String name;
> private Set addresses = new HashSet();
> 
> public String getName() {
> return name;
> }
> public void setName(String name) {
> this.name = name;
> }
> 
> 
> public Set getAddresses() {
> return addresses;
> }
> public void setAddresses(Set addresses) {
> this.addresses = addresses;
> }
> }
> 
> //are complete constructors required?


Neither constructors nor setters are required.

> -
> 
> public class Address {
> 
> private String address1;
> 
> public String getAddress1() {
> return address1;
> }
> public void setAddress1(String address1) {
> this.address1 = address1;
> }
> 
> }
> 
> --
> 
> public void personsFromXML(MultipartFile xml) {
> XStream xstream = new XStream(new StaxDriver());
> Persons persons = new Persons();
> xstream.alias("persons", Persons.class);
> 
> try {
> persons = (Persons)xstream.fromXML(xml.getInputStream());
> 
> }
> catch(Exception e){
> e.printStackTrace();
> }
> 
> --
> 
> i have tried annotations in Persons.class as well as all variations of the
> below (+ others):
> //xstream.addImplicitCollection(Person.class, "person");
> //xstream.alias("persons", Persons.class);
> //xstream.alias("person", Person.class);
>//xstream.alias("address", Address.class);
> //xstream.addImplicitCollection(Person.class, "person");
> //xstream.addImplicitCollection(Person.class, "person",
> Persons.class);
> //xstream.addImplicitCollection(Persons.class, "person",
> Person.class);


http://xstream.codehaus.org/faq.html#XML_unmarshalling_fails

Therefore adjust the marshalling. If XStream generates the required XML 
format, it can also read it. It is a very tedious and annoying task to try 
it the other way round (you already found this out), because you never know 
- especially as starter - why XStream throws an exception or silently skips 
some elements.

 
> how does xstream know that collection A is within Persons.class, but
> collection B is in Person.class?


Java reflection.


> are the generic converters being used when xtream performs its
> auto-deserialization magic?


Since XStream has obviously no built-in converters for Person or Address, it 
has to use the generic converters (based on reflection).


> are aliases and implicitCollections handled diff when marshall v.
> unmarshall?


No. That's the point. Adjust the XStream and write an object as XML and you 
will see immediately what has been influenced.

Hope this helps,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: JavaBeanConverter vs @XStreamAsAttribute

2014-05-16 Thread Jörg Schaible
Hi Lethal,

Lethal Possum wrote:

> Hello Jörg,
> 
> Thank you for your quick and clear answer.
> 
> I am trying to migrate an existing code base from JAXB to XStream, to
> compare the unmarshalling speed and the ease of use of both frameworks.

Well, I guess JAXB will process the XML faster, just because it uses 
generated stubs to read/write the predefined XML. However, biggest drawback 
is, that you will have to generate different stubs for different versions of 
your schema and it gets even more difficult, if you have to process multiple 
XML versions of your schema without knowing which one in advance. Here you 
can provide custom converters in XStream that can read old and new format at 
the same time.

> Currently our JAXB annotations use the accessors. I wanted to do the same
> in XStream in case some of the accessors have some extra logic in it and
> also to make the benchmark as fair as possible.
> 
> I will review our accessors and if none of them do anything special, I
> guess accessing the fields directly is not a big issue.

One general advice: Instantiating an XStream instance and setting it up is a 
very expensive operation. Therefore you should do this only once and then 
reuse the prepared instance every time. You may use this instance even 
concurrently since marshalling/unmarshalling is threadsafe.

If you have to optimize extremely for speed, you should create custom 
converters for your objects instead of using the default ones based on 
reflection. This will have a similar effect compared to the JAXB stubs.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: JavaBeanConverter vs @XStreamAsAttribute

2014-05-15 Thread Jörg Schaible
Hello LP,

Lethal Possum wrote:

> Hello everyone,
> 
> I am a new to XStream user and I have an issue that might be very simple
> but I am not able to figure it out.
> 
> Let's say I have the following XML:
> 
> 
>bar
> 
> 
> I would like to use the JavaBeanConverter to force the unmarshalling to go
> through my setters but when I register the JavaBeanConverter, my
> XStreamAsAttribute annotations seem to stop working.

[snip]

> With the JavaBeanConverter registered, I see the print message in
> setName() but not the one in setId() and the id field remains null. If I
> comment it out, I do not go through the setters but id's value is correct.
> What am I missing?

The current implementation for the attribute support (and other stuff) is 
completely based on reflection. Therefore the JavaBeanConverter has 
currently no support for attributes, since the property name of a bean does 
not have to correspond in any way with the internal field name of a member 
of the bean. Sorry.

Unfortunately this is nothing we can change in short time, since it requires 
a most-probably incompatible redesign of the registration and lookup part.

> Thanks in advance for your help.

What do you try to achieve with the calling of the setters?

- Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Map> | Convert To XML

2014-05-15 Thread Jörg Schaible
Hello Raj,

Raj wrote:

> Jörg Schaible  writes:
> 
>> 
>> Jörg Schaible wrote:
>> 
>> > Hi Raj,
>> > 
>> > Raj wrote:
>> > 
>> >> Hi
>> >> 
>> >> Thanks for quick repsonses.
>> >> 
>> >> I have map below.
>> >> 
>> >> Map> desksDetails = new HashMap> >> Set>();
>> >> 
>> >> Map key is "ABC"
>> >> and value is Set holding usernames.
>> >> 
>> >> I want to covert this into xml like
>> >> 
>> >> 
>> >> 
>> >> 
>> >> 
>> >> 
>> >> 
>> >> 
>> >> 
>> >> 
>> >> I looked into NamedMapConverter but the map here is key,value as
> String.
>> >> In my case value is collection.
>> >> 
>> >> Any pointer will be higly appreciated.
>> > 
>> > 
>> > Did you try:
>> > 
>> >  new NamedMapConverter(xstream.getMapper(), "desk", "name",
> String.class,
>> >null, HashSet.class, true, false, xstream.getConverterLookup());
>> > 
>> > That should be written as:
>> > 
>> >  
>> >
>> >   rpaynter
>> >   
>> >
>> >  
>> > 
>> > You will have to register an additional NamedCollectionConverter for
>> > HashSet in general though to influence the inner set. However, that
> would
>> > affect any HashSet in your object graph.
>> > 
>> > The only alternative is otherwise a gain a custom converter, probably
>> > derived from the MapConverter.
>> 
>> Actually there's a third option by injecting a modified ConverterLookup:
>> 
>>   new NamedMapConverter(xstream.getMapper(), "desk", "name",
>>   String.class,
>> null, HashSet.class, true, false, new ConverterLookup() {
>>   Override
>> Converter lookupConverterForClass(Class type) {
>>   if (type == HashSet.class) {
>> return new NamedCollectionConverter( ... );
>>   } else
>> return
>> xstream.getConverterLookup().lookupConverterForClass(type);
>> }
>>   });
>> 
>> You get the idea ...
>> 
>> Cheers,
>> Jörg
>> 
>> -
>> To unsubscribe from this list, please visit:
>> 
>> http://xircles.codehaus.org/manage_email
>> 
>> 
> 
> 
> Hi
> 
> Actually i am using the custom converter.
> 
> so i am doing something like
> 
> public void marshal(Object source, HierarchicalStreamWriter writer,
> MarshallingContext context) {
> MCS mcs = (MCS) source;
> //couple of the other customization here
> if(mcs.getDesks()!=null)
> context.convertAnother(mcs.getDesks(),new DeskCollectionConverter());
> 
> }


Normally you use a ConverterLookup instead of instantiating converters 
types, because the converter instances are typically reused. However, my 
solution from above was not that different in the end. You may create the 
converter in the constructor though and keep it as member to reuse it.

 
> Now i want my DeskCollectionConverter to extend NamedCollectionConverter.
> 
> The
> NamedCollectionConverter constructor parameters are
> NamedCollectionConverter(Class type, Mapper mapper, String itemName, Class
> itemType)
> 
> How to pass these parameters ?


The only parameter you should be curious about is the Mapper. All the others 
should be known. Normally you pass the Mapper in with the constructor of 
your "outer" converter:

== %< =
 class YourCustomConverter extends Converter {
   Converter collectionConverter;
   YourCustomConverter(Mapper mapper) {
 collectionConverter = new DeskCollectionConverter(mapper);
   }
 }
== %< =

> I am learning and soon will be perfect with XStream.

Fine. ;-)

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Map> | Convert To XML

2014-05-12 Thread Jörg Schaible
Jörg Schaible wrote:

> Hi Raj,
> 
> Raj wrote:
> 
>> Hi
>> 
>> Thanks for quick repsonses.
>> 
>> I have map below.
>> 
>> Map> desksDetails = new HashMap> Set>();
>> 
>> Map key is "ABC"
>> and value is Set holding usernames.
>> 
>> I want to covert this into xml like
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> I looked into NamedMapConverter but the map here is key,value as String.
>> In my case value is collection.
>> 
>> Any pointer will be higly appreciated.
> 
> 
> Did you try:
> 
>  new NamedMapConverter(xstream.getMapper(), "desk", "name", String.class,
>null, HashSet.class, true, false, xstream.getConverterLookup());
> 
> That should be written as:
> 
>  
>
>   rpaynter
>   
>
>  
> 
> You will have to register an additional NamedCollectionConverter for
> HashSet in general though to influence the inner set. However, that would
> affect any HashSet in your object graph.
> 
> The only alternative is otherwise a gain a custom converter, probably
> derived from the MapConverter.

Actually there's a third option by injecting a modified ConverterLookup:

  new NamedMapConverter(xstream.getMapper(), "desk", "name", String.class,
null, HashSet.class, true, false, new ConverterLookup() {
@Override
Converter lookupConverterForClass(Class type) {
  if (type == HashSet.class) {
return new NamedCollectionConverter( ... );
  } else
return xstream.getConverterLookup().lookupConverterForClass(type);
}
  });

You get the idea ...

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Map> | Convert To XML

2014-05-12 Thread Jörg Schaible
Hi Raj,

Raj wrote:

> Hi
> 
> Thanks for quick repsonses.
> 
> I have map below.
> 
> Map> desksDetails = new HashMap>();
> 
> Map key is "ABC"
> and value is Set holding usernames.
> 
> I want to covert this into xml like
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> I looked into NamedMapConverter but the map here is key,value as String.
> In my case value is collection.
> 
> Any pointer will be higly appreciated.


Did you try:

 new NamedMapConverter(xstream.getMapper(), "desk", "name", String.class,
   null, HashSet.class, true, false, xstream.getConverterLookup());

That should be written as:

 
   
  rpaynter
  
   
 

You will have to register an additional NamedCollectionConverter for HashSet 
in general though to influence the inner set. However, that would affect any 
HashSet in your object graph.

The only alternative is otherwise a gain a custom converter, probably 
derived from the MapConverter.

- Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Class member variables as attribute to itself

2014-05-11 Thread Jörg Schaible
Hi Raj,

Raj wrote:

> Hi
> 
> I have spend lot of time but could not create xml like
> 
> How to achieve xml like
> 
>   
>   Walnes
> 
> 
> If i have person object like
> public class Person {
>   private String firstname;
>   private String lastname;
> }
> 
> The above sample give the output at xml like
> 
>   Joe
>   Walnes
> 
> 
> Code:
> public class Person {
>   private String firstname;
>   private String lastname;
> }
> 
> 
> Person joe = new Person("Joe", "Walnes");
> String xml = xstream.toXML(joe);
> 
>  
> Any help will be appreciated.

You can configure XStream to use an attribute instead of an element, but you 
cannot have both. This is exactly a situation where you have to write an own 
custom converter. Since you've already looked at the tutorial, you should be 
able to write one.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: What is Benefit of Converter?

2014-05-09 Thread Jörg Schaible
Hi Raj,

Raj wrote:

> Hi
> 
> 
> What is the purpose of com.thoughtworks.xstream.converters.Converter
> Class.
> 
> 
> I look for demo
> http://xstream.codehaus.org/converter-tutorial.html
> 
> 
> Without converter class, the output is
> 
> 
>   Guilherme
> 
> 
> With converter class, the output is
> 
>   Guilherme
> 
> 
> But we can achieve output same as tag name  with
> 
> @XStreamAlias("fullname")
> private String name;
> 
> So what is the benefit of using converter.

It is a simple example of how to write one.

;-)

- Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Namespace id attributes

2014-04-09 Thread Jörg Schaible
Hi Geoffrey,

Geoffrey De Smet wrote:

> I am using
>xStream.setMode(XStream.ID_REFERENCES);
> But some of my classes have a @XStreamAsAttribute field called "id".
> 
> 
> So I get output like this:
>
> 
> Can I namespace the xstream id attribute somehow, so I get this instead:
> 

No, XStream uses the default namespace and none of its XML parsers are 
actually configured to actually support namespaces (except of the StaxDriver 
and derived).

However, you can set a systemAlias to use a different attribute name.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: @XStreamImplicit() for a field which is not a collection

2014-04-07 Thread Jörg Schaible
Hi Geoffrey,

Geoffrey De Smet wrote:

> How do I model a singleton field of a supertype of several types with
> different element names?
> 
> 
> I have these classes:
> 
> @XStreamAlias("house")
> public class House {
> 
>  @XStreamImplicit()
>  private List animalList;
> 
> }
> 
> @XStreamInclude({Dog.class, Cat.class})
> public abstract class Animal {}
> 
> @XStreamAlias("dog")
> public class Dog extends Animal {}
> 
> @XStreamAlias("cat")
> public class Cat extends Animal {}
> 
> so I can write:
> 
> 
>
>
>
> 
> 
> and the animalList of House is filled with 2 dogs and a cat.
> This works well.
> 
> 
> Now I want to be able to do support an xml like this:
> 
>
> 
> or
> 
>
> 
> 
> and a class diagram that doesn't use a List field, but just a
> field Animal:
> 
> @XStreamAlias("cage")
> public class Cage {
> 
>  @XStreamImplicit()
>  private Animal animal;
> 
> }
> 
> But that doesn't work.

Implicit declaration is only meaningful for List, Map or Array types.

> How can I make that work?

Not by configuration. The Cage member will alway be named 'animal'. An alias 
cannot do, since it maps only the name of the member ... you want to map the 
member instance's type.

> Without changing the XML schema.
> Currently I am working around by using an List anyway,
> and adding validation that it's a singleton list... but that's undesired.

Create a custom converter for Cage and write the XML tag yourself using the 
Animal's real type. If you provide the current Mapper as constructor 
argument. you can lookup the aliases for Dog.class and Cat.class. See the 
example at the end of the converter-tutorial, how you can pass the 
marshalling of the member itself again to XStream.

Cheers,
Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Externalizable & readResolve

2014-03-27 Thread Jörg Schaible
Jörg Schaible wrote:

> Hi Derek,
> 
> Trumbo, Derek wrote:
> 
>> Hello,
>> 
>> I had some trouble researching whether or not this was still an issue, so
>> I apologize in advance if this too commonly asked.  I saw a post from a
>> long time ago indicating that readResolve is not called on an object that
>> implements Externalizable.  I am experiencing the same issue (1.4.7).
>> Before posting code, I figured I'd ask as to the status of this issue,
>> whether it was thought to be fixed, or still an outstanding issue. 
>> Thanks so much!
> 
> actually it's the first time, I hear complaints about this. However,
> Javadoc of Externalizable explicitly states "These methods (writeExternal
> and readExternal) supersede customized implementations of writeObject and
> readObject methods." i.e. it would be wrong to call readResolve().

Hehehe, I should have read better. Yes, you're right, an Externalizable may 
use writeReplace and readResolve and you're right again, the 
ExternalizableConverter does not honor the situation.

Please open a JIRA issue.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Externalizable & readResolve

2014-03-27 Thread Jörg Schaible
Hi Derek,

Trumbo, Derek wrote:

> Hello,
> 
> I had some trouble researching whether or not this was still an issue, so
> I apologize in advance if this too commonly asked.  I saw a post from a
> long time ago indicating that readResolve is not called on an object that
> implements Externalizable.  I am experiencing the same issue (1.4.7). 
> Before posting code, I figured I'd ask as to the status of this issue,
> whether it was thought to be fixed, or still an outstanding issue.  Thanks
> so much!

actually it's the first time, I hear complaints about this. However, Javadoc 
of Externalizable explicitly states "These methods (writeExternal and 
readExternal) supersede customized implementations of writeObject and 
readObject methods." i.e. it would be wrong to call readResolve().

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: Re: Custom Serializer Issue

2014-03-13 Thread Jörg Schaible
Hi Robert,

Robert Feustel wrote:

> All right,
> 
> This pretty much works. Only deserialization doesn't work quite
> allright, but I have found the problem and multiple solutions to that.
> So, here's what I've done:
> 
> class ProperSerializableConverter extends SerializableConverter {
> ProperSerializableConverter(Mapper mapper, ReflectionProvider
> reflectionProvider, ClassLoaderReference classLoaderReference) {
>   super(mapper, reflectionProvider, classLoaderReference);
> }
> boolean canConvert(Class type) {
>   if (type.getPackage() != null &&
>   type.getPackage().startswith(yourPackagePath) && type instanceof
>   Serializable)
> return true;
>   return false; }
> protected void marshalUnserializableParent(HierarchicalStreamWriter
> writer, MarshallingContext context, Object replacedSource) {
>   // do nothing on purpose
> }
>   }
> 
> 
> This will make it work for all my classes easily. However, I have
> encountered a little oddity:
> 
> abstract class A {
> 
>private LinkedList stringList = new LinkedList();
> 
> }
> 
> class B extends A implements Serializable {
> 
> // some properties and de-/serialization methods
> 
> }
> 
> Serializing and deserializing an Object of class B through java will
> work. Through xstream however the LinkedList in class A will not be
> initialized during deserialization. I don't know what java and xstream
> do or don't do here. Maybe you can have a look at this. I don't mind
> working around it. I already have two ideas I will try on monday,
> though. (Do I have to write a deserializer for that?)

Normally neither Java (de-)serialization nor XStream unmarshalling will run 
class initializers or constructors. Possibly Java deserialization makes an 
exception here for this rule for unserializable parents, since it requires 
those to have a default constructor. However, there's no official way to run 
parent's class initializers or default constructors without actually 
constructing an object.

> However I've encountered another (more important) problem.
> If I use my custom serialization, I don't get the property names...
> Yeah, I didn't consider that... So now here's a new question: Is it
> possible to not use the custom serialization, even if there is one? Or,
> is it possible to somehow feed the property names into the process?
> Although I wouldn't know how that would be done without breaking java
> serialization...

?? You mean, you want to define the names of the XML tags used for the 
objects written in your writeObject method? Sorry, this is not possible at 
all. You write the pure objects, so this is all that XStream gets.

If you have special requirements here for your XML, you will have to write a 
complete custom converter(s) for your type(s), have a look at the converter 
tutorial. This is not difficult, but you will have to keep the code in the 
custom converter and the serialization methods logically in sync on your 
own, because those two methods are then no longer relevant for the 
marshalling process of XStream.

> Thank you for all your help,

Your welcome.

Cheers,
Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: Custom Serializer Issue

2014-03-12 Thread Jörg Schaible
Hi Robert,

Robert Feustel wrote:

> Hiho Jörg,
> 
> The problem appears to be that xstream is (in contrast to the default
> serialization?) automatically trying to serialize parent classes as
> well... Even if they aren't serializable (I know that part is not a bug,
> but a feature ;))

Actually, it is ... since XStream serializes any type, not just Serializable 
ones. And XStream cannot tell, whether the implementation of a Serializable 
type actually handles such a case on purpose or the type was never meant to 
be serialized with Java serialization and therefore does not handle the 
situation.

> Can I turn that off somehow? This is what breaks my xstream, because
> there are some objects referenced there that cannot be serialized using
> a standard ObjectOutputStream. And they shouldn't be in the xml in the
> first place, because they are (although not marked) transient. I really
> don't want to have to recheck my entire hierarchy for that.

It's nothing you can configure, but you can create a customized 
SerializationConverter:

 %< ===
 class ProperSerializableConverter extends SerializableConverter {
   ProperSerializableConverter(Mapper mapper, ReflectionProvider 
reflectionProvider, ClassLoaderReference classLoaderReference) {
 super(mapper, reflectionProvider, classLoaderReference);
   }
   boolean canConvert(Class type) {
 return type == YourType.class;
   }
   protected void marshalUnserializableParent(HierarchicalStreamWriter 
writer, MarshallingContext context, Object replacedSource) {
 // do nothing on purpose
   }
 }

 xstream.registerConverter(
   new ProperSerializableConverter(
 xstream.getMapper(),
 xstream.getReflectionProvider(),
 xstream.getClassLoaderReferenfce()));
 %< ===

> Or should I really implement a serialization method for the parent?
> Parent data is stored during serialization, but I just moved that to the
> child classes (parent is abstract and most data in it not serialized
> anyway)...
> 
> Looking forward to hearing from you,

I did not test the solution above, but it should be working since the whole 
unserializable-parent element is simply omitted.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Custom Serializer Issue

2014-03-12 Thread Jörg Schaible
Hi Robert,

Robert Feustel wrote:

> Hello there,
> 
> I'm trying to serialize a complex object that I wrote
> a custom serializer (write/readObject() method) for. Now, when I try
> running this through xstream it appears that this custom serializer is
> completely ignored... It's a hierarchical dataset containing multiple
> instances (in depth as well as width) of custom objects with custom
> serialization methods...
> 
> Is there a way to tell xstream to only use
> the serialization that java uses... The one I specified?

XStream respects those serializers by default (*), why do you think 
otherwise? Marshal such an object to XML and back again and ensure either 
with the debugger or System.println() calls that your methods have been 
called.

*) Without XStream annotations or further configuration, just by:

 %< 
 XStream xstream = new XStream();
 String xml = xstream.toXML(yourObject);
 YourType yourObjectAgain = (YourType)xstream.fromXML(xml);
 %< 

However, you might have influenced this depending on your XStream setup.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: Need help with a custom converter

2014-03-06 Thread Jörg Schaible
Hi,

to me this looks like you deserialize with that ReflectionConverter and 
serialize without it ... this will not work. XStream must be setup in the 
same way for both operations.

- Jörg




X wrote:

> So I made the update and it seemed to work, I was able to bring up the
> object.  But with testing I noticed that all the objects that I
> unmarshalled and then were updated and reserialized with xstream would
> cause the following exception when I would try to unmarshall it again:
> 
> 
> [exec] Caused by:
> 
com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException:
> No such field
> 
com.sun.org.apache.xerces.internal.dom.AttributeMap.com.sun.org.apache.xerces.internal.dom.NamedNodeMapImpl
> [exec]  Debugging information  [exec] field   :
> com.sun.org.apache.xerces.internal.dom.NamedNodeMapImpl [exec] class  
> : com.sun.org.apache.xerces.internal.dom.AttributeMap
> [exec] required-type   :
> com.sun.org.apache.xerces.internal.dom.AttributeMap [exec] converter-type 
> : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
> [exec] path:
> 
/xxx.xxx.SignedDocument/template/template/com.sun.org.apache.xerces.internal.dom.NodeImpl/default/ownerNode/com.sun.org.apache.xerces.internal.dom.ElementImpl/default/attributes/com.sun.org.apache.xerces.internal.dom.NamedNodeMapImpl
> [exec] line number : 566
> [exec] class[1]:
> com.sun.org.apache.xerces.internal.dom.ElementImpl
> [exec] converter-type[1]   :
> com.thoughtworks.xstream.converters.reflection.SerializableConverter
> [exec] class[2]:
> xxx.xxx.MyTemplate
> [exec] class[3]: xxx.xxx.SignedDocument
> [exec] version : 1.4.7
> 
> Is there anything I can do about this?
> 
> 
> 
> On Thursday, March 6, 2014 8:39 AM, X
>  wrote: Thank you sooo much
> for your help!
> 
> 
> 
> 
> On Thursday, March 6, 2014 4:04 AM, Jörg Schaible
>  wrote: Hi,
> 
> X wrote:
> 
>> I'm getting this exception:
>> 
> 
[exec]Causedby:com.thoughtworks.xstream.converters.ConversionException:Cannotdeserialize
>> [objectwithnewreadObject()/writeObject()methods
>> [[exec]Debugginginformation
>> 
> 
[[exec]class:com.sun.org.apache.xerces.internal.dom.AttributeMap[exec]required-
> type
>> [:com.sun.org.apache.xerces.internal.dom.AttributeMap[exec]converter-type
>> 
> 
[:com.thoughtworks.xstream.converters.reflection.SerializableConverter[exec]path
>> 
> 
[:/xxx.xxx.xxx.xxx.xxx.xxx.SignedDocument/template/template/com.sun.org.apache.xerces.internal.dom.NodeImpl/default/ownerNode/com.sun.org.apache.xerces.internal.dom.ElementImpl/default/attributes
>> [[exec]line number
>> 
> 
[:1183[exec]class[1]:com.sun.org.apache.xerces.internal.dom.ElementImpl[exec]class[2]:xxx.xxx.xxx.xxx.xxx.xxx.MyTemplate[exec]converter-
> type[1]:com.thoughtworks.xstream.converters.r
>>
> 
eflection.ReflectionConverter[exec]class[3]:xxx.xxx.xxx.xxx.xxx.xxx.SignedDocument[exec]version
>>:1.4.5[exec]---
>> 
>> I know that the problem is that the xml file was created under JDK 6 and
>> since we've updated to JDK 7, the reflection-based converter broke.  I
>> did not write this code and have no experience with XStream though, so I
>> am not sure how to create the custom converter.  The xml I'm trying to
>> unmarshal from is a mess.  It's got an element named "template" of a
>> certain class type that is a child of another element with the same
>> "template" name but with a different class type.  And within the
>> inner-"template" element are all these sub-elements called
>> com.sun.org.apache.xerces.internal.dom.NodeImpl,
>> com.sun.org.apache.xerces.internal.dom.ChildNode,
>> com.sun.org.apache.xerces.internal.dom.ParentNode,
>> com.sun.org.apache.xerces.internal.dom.ElementImpl.  I just don't even
>> know where to start or what cl
>>ass I'm supposed to try to create a custom converter for.
> 
> This is really a nasty one. The problem is that the internal layout of the
> AttributeMap has changed. Actually the change happened in the parent class
> NamedNodeMapImpl. That one has now a method pair of readObject/writeObject
> to mask the fact that it manages its nodes no longer in a Vector but an
> arbitrary List implementation. The SerializableConverter detects this
> situation and - because in those methods can happen "anything - it is no
> longer able to deserialize.
> 
> Since those methods were not present in Java 6 and AttributeMap and its
> super classes were all Serializable an

[xstream-user] Re: Need help with a custom converter

2014-03-06 Thread Jörg Schaible
Hi,

X wrote:

> I'm getting this exception:
> 
[exec]Causedby:com.thoughtworks.xstream.converters.ConversionException:Cannotdeserialize
> [objectwithnewreadObject()/writeObject()methods
> [[exec]Debugginginformation
> 
[[exec]class:com.sun.org.apache.xerces.internal.dom.AttributeMap[exec]required-
type
> [:com.sun.org.apache.xerces.internal.dom.AttributeMap[exec]converter-type
> 
[:com.thoughtworks.xstream.converters.reflection.SerializableConverter[exec]path
> 
[:/xxx.xxx.xxx.xxx.xxx.xxx.SignedDocument/template/template/com.sun.org.apache.xerces.internal.dom.NodeImpl/default/ownerNode/com.sun.org.apache.xerces.internal.dom.ElementImpl/default/attributes
> [[exec]line number
> 
[:1183[exec]class[1]:com.sun.org.apache.xerces.internal.dom.ElementImpl[exec]class[2]:xxx.xxx.xxx.xxx.xxx.xxx.MyTemplate[exec]converter-
type[1]:com.thoughtworks.xstream.converters.r
>  
eflection.ReflectionConverter[exec]class[3]:xxx.xxx.xxx.xxx.xxx.xxx.SignedDocument[exec]version
>  :1.4.5[exec]---
> 
> I know that the problem is that the xml file was created under JDK 6 and
> since we've updated to JDK 7, the reflection-based converter broke.  I did
> not write this code and have no experience with XStream though, so I am
> not sure how to create the custom converter.  The xml I'm trying to
> unmarshal from is a mess.  It's got an element named "template" of a
> certain class type that is a child of another element with the same
> "template" name but with a different class type.  And within the
> inner-"template" element are all these sub-elements called
> com.sun.org.apache.xerces.internal.dom.NodeImpl,
> com.sun.org.apache.xerces.internal.dom.ChildNode,
> com.sun.org.apache.xerces.internal.dom.ParentNode,
> com.sun.org.apache.xerces.internal.dom.ElementImpl.  I just don't even
> know where to start or what cl
>  ass I'm supposed to try to create a custom converter for.

This is really a nasty one. The problem is that the internal layout of the 
AttributeMap has changed. Actually the change happened in the parent class 
NamedNodeMapImpl. That one has now a method pair of readObject/writeObject 
to mask the fact that it manages its nodes no longer in a Vector but an 
arbitrary List implementation. The SerializableConverter detects this 
situation and - because in those methods can happen "anything - it is no 
longer able to deserialize.

Since those methods were not present in Java 6 and AttributeMap and its 
super classes were all Serializable and did lack such a method pair, the 
generated XML does actually not differ from the one that would have been 
produced by the ReflectionConverter itself. So in this special case you can 
get away registering a ReflectionConverter for AttributeMap:

== %< 
 xstream.register(
   new ReflectionConverter(
 xstream.getMapper(), 
 xstream.getReflectionProvider(),
 AttributeMap.class));
== %< 

The Java code and the XML will be compatible for both Java versions.

However, in the long run, you should think about custom converters for all 
those DOM types - or one for the root element of the DOM objects in your 
classes (typically a Document) and write/recreate the XML structure using 
the methods of XStream's reader/writer.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: weird xstream problem

2014-02-27 Thread Jörg Schaible
Hi,

sc wrote:

> Hi,
> 
> I am facing an xstream issue that I just cant figure out a solution to. An
> help is much appreciated.
> 
> I have an XML that looks like
> 
> 
>
>
>
>10
>10
>
>
> 
> 
> This XML needs to be converted to the following Object hierarchy:
> 
> class parent {
>  private 
>  private 
>  private 
>  private Child child;
>  private 
>  private 
> }
> class Child {
>  private int sonAge;
>  private int daughterAge;
> }
> 
> 
> I cannot change the format of the XML as it is coming from another system.
> 
> Also having it converted to something like the following is NOT an option
> either.:
> class parent {
>  private 
>  private 
>  private 
>  private int childSonAge;
>  private int childDaughterAge;
>  private 
>  private 
> }
> 
> I spend quiet a bit of time looking for a solution online but just cant
> get it to work.

XStream is basically from Java to XML and back, i.e. the Java object graph 
dictates the XML structure. Therefore you will not find any configuration 
possibility or other automatism in XStream to flatten the Child element into 
two XML elements of the parent. You will have to write a custom converter 
for your parent class. However, that's quite easy, have a look at the 
converter tutorial: http://xstream.codehaus.org/converter-tutorial.html

Then a major rule of thumb: Always serialize your objects to XML and tweak 
the output until it matches the XML you'd like to read. Anything else will 
be an annoying experience, because then you will have to guess on your own 
what XML format XStream currently understands.

Looking at your XML it seems also that you will have a general mapping from 
underscore separated words to camel case (and vice versa). Have a look at 
com.thoughtworks.acceptance.CustomMapperTest.FieldPrefixStrippingMapper how 
to implement such a general name mapping with a custom Mapper.

Also, since underscores are involved, look at FAQ: 
http://xstream.codehaus.org/faq.html#XML_double_underscores

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: RE: 1.4 JVM version

2014-02-26 Thread Jörg Schaible
mrs.nospam wrote:

> unsubscribe

Your own task
http://xircles.codehaus.org



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: Re: Re: Set both collection name and item name

2014-02-26 Thread Jörg Schaible
Hi Paul,

Paul B. Anderson wrote:

> I made the changes you suggested and everything is working as desired.
> Thank you again.
> 
> I'm curious, in the annotation version, how can I know what parameters
> the annotation takes?  I see how the XStream facade works in the JAVADOCs.

Its explained in the Javadocs for @XStreamConverter (and in the thread here 
on the mailing list last week about the CollectionConverter in combination 
with this annotation).

In short: XStream uses a poor man's dependency injection (DI) when 
instantiating a Converter by looking at its constructors. Apart from 
internal objects (like the Mapper) you can define additional constants of 
various types with the annotation. The DI algorithm starts matching the 
constructor with the highest number of arguments with all available possible 
arguments and uses it if it matches successful. It respects definition 
sequences i.e. the first string constant defined in the annotation will be 
passed as the first String argument of the constructor.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: Re: Set both collection name and item name

2014-02-25 Thread Jörg Schaible
Hi Paul,

Paul B. Anderson wrote:

> I managed to create three almost identical converters for the three
> ArrayList elements of my Java structure and I can both read and
> write XML in the desired format.
> 
> I was unable to see how to get the CollectionConverter or
> NamedCollectionConverter to fit in.  I don't have distinct types for the
> three lists and the examples I saw assumed a distinct type for the
> collection.

?? You register an individual instance of the NamedCollectionConverter as 
local converter directly for each list ... why do you assume you have to 
have distinct types?

> 
> I was trying to use the annotation approach because that seemed to be
> the only way to be specific about which of the ArrayLists I was
> referring to.  It was not clear how to proceed and trial and error was
> not effective for me.
> 
> What I would really like is an annotation or combination of annotations
> that combines a top level alias with an implicit alias, something like
> 
>@XStreamCollection("movies", "title")
>ArrayList movies;
> 
>@XStreamCollection("plays", "title")
>ArrayList plays;

  @XStreamConverter(value=NamedCollectionConverter.class, strings={"title"}, 
types={String.class})
  ArrayList movies;
 
  @XStreamConverter(value=NamedCollectionConverter.class, strings={"title"}, 
types={String.class})
  ArrayList plays;

produces:
 
> etc., producing
>...
>
>  Title 1
>  Title 2
>
>
>  Title 1
>  Title 2
>

This XML is *not* implicit, since you have a surrounding tag for your 
elements - at least this is what *implicit* everywhere means for XStream.

> It seems to me that simple collections or maps are somewhat special.  If
> it were more complex than a simple collection, a person would typically
> want to develop a class but for just a list of items a special class is
> much less compelling.

You don't have to. The alternative would have been to register the local 
converters using the XStream facade. Funny enough, the converter instance 
can be the same here, because the name and type of the items are the same 
(assuming Foo is the name of the class containing those two lists):

  Converter namingConverter = new NamedCollectionConverter(
xstream.getMapper(), "title", String.class);
  xstream.registerLocalConverter(Foo.class, "movies", namingConverter);
  xstream.registerLocalConverter(Foo.class, "plays", namingConverter);


Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: Set both collection name and item name

2014-02-24 Thread Jörg Schaible
Hi Paul,

Paul B. Anderson wrote:

> I'm still struggling.  Where can I find ParameterizedConverterTest?

https://fisheye.codehaus.org/browse/xstream/trunk/xstream/src/test/com/thoughtworks/acceptance/annotations/ParametrizedConverterTest.java?r=2131

> One additional aspect:  I have three instances of the ArrayList
> in my object, each with different inner element names.

Register a local converter for each instance.

Also have a look at the parallel thread with the CollectionConverter and 
@XStreamConverter annotation.

Cheers,
Jörg


> 
> On 2/24/14 1:46 PM, Jörg Schaible wrote:
>> Hi Paul,
>>
>> Paul B. Anderson wrote:
>>
>>> I'm trying to handle an ArrayList to achieve XML like the
>>> following:
>>>
>>>  
>>>Alpha
>>>Bravo
>>>Charlie
>>>  
>>>
>>> The examples Ive seen let me name the outer  element or
>>> eliminate the outer element and name the inner elements. Is there a way
>>> to
>>> achieve both?  I'm using annotations but I'm not tied to them.
>> Register a local converter of type NamedCollectionConverter for the
>> field. This is also possible with annotations, but a bit tedious. You may
>> have a look at the ParameterizedConverterTest for an example.
>>
>> Cheers,
>> Jörg
>>
>>
>> -
>> To unsubscribe from this list, please visit:
>>
>>  http://xircles.codehaus.org/manage_email
>>
>>
>>
> 
> 
> -
> To unsubscribe from this list, please visit:
> 
> http://xircles.codehaus.org/manage_email



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Set both collection name and item name

2014-02-24 Thread Jörg Schaible
Hi Paul,

Paul B. Anderson wrote:

> I'm trying to handle an ArrayList to achieve XML like the
> following:
> 
> 
>   Alpha
>   Bravo
>   Charlie
> 
> 
> The examples Ive seen let me name the outer  element or
> eliminate the outer element and name the inner elements. Is there a way to
> achieve both?  I'm using annotations but I'm not tied to them.

Register a local converter of type NamedCollectionConverter for the field. 
This is also possible with annotations, but a bit tedious. You may have a 
look at the ParameterizedConverterTest for an example.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] RE: RE: RE: Re: Using CollectionConverter with @XStreamConverter

2014-02-24 Thread Jörg Schaible
Hi Dmtry,

depst...@alliedtesting.com wrote:

 ?!? What is XStream 1.4.6.1? We release 1.4.6 and 1.4.7, but nothing
 inbetween.
>>> 
>>> Yeah, sorry, that was an OSGi bundle version. The XStream version is
>>> 1.4.6.
> 
>>Is there something wrong with the OSGi info in 1.4.6?
> 
> I don't know. Has XStream released an OSGi bundle for 1.4.6? Mine comes
> from a different source (Apache). I don't remember the reasons why we get
> our bundles from a third party.

OSGi bundle is present since version 1.4.5 (see minor changes of 
http://xstream.codehaus.org/changes.html#1.4.5):

== %< ==
$ catmf xstream-1.4.6.jar
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven Bundle Plugin
Built-By: joehni
Build-Jdk: 1.7.0_45
Specification-Title: XStream Core
Specification-Vendor: XStream
Implementation-Title: XStream Core
Implementation-Version: 1.4.6
Implementation-Vendor-Id: com.thoughtworks.xstream
Implementation-Vendor: XStream
Specification-Version: 1.4
X-Build-Os: Linux
X-Build-Time: 20131212-1854
X-Builder: Maven 3.0.5
X-Compile-Source: 1.5
X-Compile-Target: 1.5
Bnd-LastModified: 1386870879781
Bundle-Description: XStream is a serialization library from Java objec
 ts to XML and back.
Bundle-DocURL: http://xstream.codehaus.org
Bundle-License: http://xstream.codehaus.org/license.html
Bundle-ManifestVersion: 2
Bundle-Name: XStream Core
Bundle-SymbolicName: xstream
Bundle-Vendor: XStream
Bundle-Version: 1.4.6
Export-Package: com.thoughtworks.xstream.io.copy;version="1.4.6",com.t
 houghtworks.xstream.io.path;version="1.4.6",com.thoughtworks.xstream.
 converters.basic;version="1.4.6",com.thoughtworks.xstream.io.xml.xppd
 om;version="1.4.6",com.thoughtworks.xstream;version="1.4.6",com.thoug
 htworks.xstream.io.json;version="1.4.6",com.thoughtworks.xstream.conv
 erters.javabean;version="1.4.6",com.thoughtworks.xstream.io;version="
 1.4.6",com.thoughtworks.xstream.converters.extended;version="1.4.6",c
 om.thoughtworks.xstream.converters;version="1.4.6",com.thoughtworks.x
 stream.converters.reflection;version="1.4.6",com.thoughtworks.xstream
 .annotations;version="1.4.6",com.thoughtworks.xstream.io.binary;versi
 on="1.4.6",com.thoughtworks.xstream.io.xml;version="1.4.6",com.though
 tworks.xstream.mapper;version="1.4.6",com.thoughtworks.xstream.persis
 tence;version="1.4.6",com.thoughtworks.xstream.converters.collections
 ;version="1.4.6",com.thoughtworks.xstream.core;version="1.4.6",com.th
 oughtworks.xstream.io.naming;version="1.4.6",com.thoughtworks.xstream
 .converters.enums;version="1.4.6"
Import-Package: com.bea.xml.stream;resolution:=optional,com.ctc.wstx.s
 tax;resolution:=optional,javax.security.auth,javax.swing,javax.swing.
 plaf,javax.xml.datatype,javax.xml.namespace;resolution:=optional,java
 x.xml.parsers,javax.xml.stream;resolution:=optional,javax.xml.transfo
 rm,javax.xml.transform.sax,javax.xml.transform.stream,net.sf.cglib.pr
 oxy;resolution:=optional,nu.xom;resolution:=optional,org.codehaus.jet
 tison;version="[1.2,2)";resolution:=optional,org.codehaus.jettison.ma
 pped;version="[1.2,2)";resolution:=optional,org.dom4j;resolution:=opt
 ional,org.dom4j.io;resolution:=optional,org.dom4j.tree;resolution:=op
 tional,org.jdom;resolution:=optional,org.jdom.input;resolution:=optio
 nal,org.jdom2;resolution:=optional,org.jdom2.input;resolution:=option
 al,org.joda.time;version="[1.6,2)";resolution:=optional,org.joda.time
 .format;version="[1.6,2)";resolution:=optional,org.kxml2.io;resolutio
 n:=optional,org.w3c.dom;resolution:=optional,org.xml.sax,org.xml.sax.
 helpers,org.xmlpull.mxp1,org.xmlpull.v1,sun.misc
Tool: Bnd-1.50.0
== %< ==

Just curious,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] RE: RE: Re: Using CollectionConverter with @XStreamConverter

2014-02-21 Thread Jörg Schaible
Hi Dmitry,

depst...@alliedtesting.com wrote:


[snip]

>> ?!? What is XStream 1.4.6.1? We release 1.4.6 and 1.4.7, but nothing
>> inbetween.
> 
> Yeah, sorry, that was an OSGi bundle version. The XStream version is
> 1.4.6.

Is there something wrong with the OSGi info in 1.4.6?

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] RE: Re: Using CollectionConverter with @XStreamConverter

2014-02-21 Thread Jörg Schaible

Hi Dmitry,

depst...@alliedtesting.com wrote:

> OK, I just realized that I misdiagnozed the problem. What actually happens
> is that CollectionConverter is initialized with the List type, because
> that is the declared type of the field. The actual type of the field
> (ArrayList) differs from the type with which the converter was
> initialized, which is why it won't work. Here is the canConvert method in
> CollectionConverter:
> 
> public boolean canConvert(Class type) {
> if (this.type != null) {
> return type.equals(this.type);
> }
> return type.equals(ArrayList.class)
> || type.equals(HashSet.class)
> || type.equals(LinkedList.class)
> || type.equals(Vector.class)
> || (JVM.is14() &&
> || type.getName().equals("java.util.LinkedHashSet"));
> }
> 
> this.type is List, and type is ArrayList. Perhaps this would be better?
> 
> return type.isAssignableFrom(this.type);

Definitely not, because XStream cannot know what else a different Collection 
implementation keeps internally. E.g. it would forget about a TreeSet's 
comparator or an unmodifiable list would no longer be unmodifiable.

> Here is a complete example:
> 
> import java.io.File;
> import java.io.FileNotFoundException;
> import java.io.PrintWriter;
> import java.util.ArrayList;
> import java.util.List;
> 
> import com.thoughtworks.xstream.XStream;
> import com.thoughtworks.xstream.annotations.XStreamConverter;
> import
> com.thoughtworks.xstream.converters.collections.CollectionConverter;
> import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import
> com.thoughtworks.xstream.io.xml.StaxDriver;
> 
> public class ItemList {
> 
> @XStreamConverter(CollectionConverter.class)
> public List items = new ArrayList();

[snip]

Look at the Javadoc for the XStreamConverter annotation. XStream performs a 
poor man's constructor dependency injection. The constructor with the most 
arguments is considered first, possible parameters are the current type (in 
your case List.class), some standard XStream objects and anything you 
provide as static parameter for the annotation.

The declaration to initialize a CollectionConverter is a bit tricky though, 
because you do *not* want to consider the current type:

@XStreamConverter(value=CollectionConverter.class, types={ArrayList.class}, 
useImplicitType = false)

Have a look at 
com.thoughtworks.acceptance.annotations.ParametrizedConverterTest for more 
examples.

[snip]

> I get an exception with XStream 1.4.6.1:

?!? What is XStream 1.4.6.1? We release 1.4.6 and 1.4.7, but nothing 
inbetween.

[snip]

Hope this helps,
Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Using CollectionConverter with @XStreamConverter

2014-02-20 Thread Jörg Schaible
Hi Dmitry,

depst...@alliedtesting.com wrote:

> Hi,
> 
> When CollectionConverter is used with the @XStreamConverter annotation,
> the converter is set up so that it will only accept the TreeMap collection
> type.

?? Sorry, I don't understand, what you try to tell me here.

> This is an odd behavior! Is there any way to suppress this
> initialization (CollectionConverter has a constructor that doesn't limit
> it to just one particular type), or to specify some other type, such as
> ArrayList?
> 
> public class ItemList {
> @XStreamConverter(value = CollectionConverter.class)
> public List items;
> }

I don't understand this example either. You setup an own CollectionConverter 
for the list, but that's the default anyway.


> 
> As a workaround, I subclassed CollectionConverter:
> 
> public class ItemList {
> @XStreamConverter(value = ListCollectionConverter.class)
> public List items;
> 
> public static class ListCollectionConverter extends
> CollectionConverter {
> public ListCollectionConverter(Mapper mapper) {
> super(mapper);
> }
> }
> }
> 
> This did the trick, but it is very counterintuitive.

Where's the difference?

Maybe you tell me first, what you actually try to accomplish...

- Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Custom hashCode and damaged collections after load

2014-02-20 Thread Jörg Schaible
Hi,

Jörg Schaible wrote:

> Hi Алексеев,
> 
> Алексеев Сергей wrote:
> 
>>Hello team. I got some question/problem with XStream.
>> 
>>I have a class with custom realization of methods equals/hashCode.
>>Such
>> objects contains in HashSet collection. Default XStream behavior: create
>> object instance, read attributes, read inner fields, return object and
>> add it to collection if needed.
>>The problem: due a specific object graph on some step of
>>deserialization
>> object was created, added to collection, and after all other fields was
>> loaded. After fields was loaded, result of hashCode was changed, causing
>> "damage" to collection (because HashSet uses HashMap inside). That
>> happens because xstream got object with null fields from cache by
>> 'refference' attribute. This does not looks like a bug, but working
>> behavior is not ideal.
> 
> Well, your object graph has circular references and at therefore it is
> simply not possible. At some stage, one of the object cannot be
> initialized fully. XStream behaves even here exactly like Java
> serialization. Let ConnectionPin and Pin both implement Serializable and
> make the serialization algorithm exchangeable:
> 
> = %< ===
> private static List serializedWithXStream(List
> inList)
> {
> /* toXML  */
> XStream xstream = new XStream();
> xstream.setMode(XStream.ID_REFERENCES);
> xstream.autodetectAnnotations(true);
> 
> String serialization = xstream.toXML(inList);
> System.out.println(serialization);
> 
> /* fromXML  */
> 
> System.out.println("\nLoad from xml\n");
> 
> List list = (List)xstream.fromXML(serialization);
> 
> System.out.println();
> return list;
> }
> 
> private static List
> serializedWithJavaSerialization(List inList) {
> try {
> /* to bytes  */
> ByteArrayOutputStream outputStream = new
> ByteArrayOutputStream();
> ObjectOutputStream oos = new ObjectOutputStream(outputStream);
> oos.writeObject(inList);
> oos.close();
> 
> /* fromXML  */
> 
> System.out.println("\nLoad from bytes\n");
> 
> ByteArrayInputStream inputStream = new
> ByteArrayInputStream(outputStream.toByteArray());
> ObjectInputStream ois = new ObjectInputStream(inputStream);
> 
> List list = (List)ois.readObject();
> 
> System.out.println();
> return list;
> } catch (IOException e) {
> throw new RuntimeException(e);
> } catch (ClassNotFoundException e) {
> throw new RuntimeException(e);
> }
> }
> = %< ===
> 
> If you run your application now calling one time the serialization with
> XStream and one time with Java serialization, you'll see, that you have
> exactly the same problems, because it is simply not possible to have the
> referring and the referred element initialized completely at the same
> time.
> 
>> In my project I fixed it by restoring collection (just recreate it with
>> same objects) in readResolve of other object (1 level upward in graph).
>>There are other problem: calling readResolve does not guarantee that
>>all
>> fields of 'this' object (including sub objects in fields) was fully
>> deserialized at moment of call. That why I cant fix collection  in
>> readResolve of object with HashSet or HashMap and should do it in other
>> place.
>> 
>>There are attach file that nicely describes a situation.
> 
> You will have to break the circle for serialization and restore it at
> deserialization time. You may consider readResolve and writeReplace
> methods that actually write/read different replacement objects or play
> with Externalizable or ...

actually it is enough to prevent the usage of the bogus hash code. Simply 
use an appropriate Set implementation:

= %< ===

...

  public static class ConnectionPin
  {
public Set inConnections = new ArraySet();
public Set outConnections = new ArraySet();
...
  } 

  @XStreamAlias( "array-set" )
  @XStreamConverter( CollectionConverter.class )
  public static class ArraySet extends AbstractSet implements Set {

private List list = new ArrayList();

@Ove

[xstream-user] Re: Custom hashCode and damaged collections after load

2014-02-19 Thread Jörg Schaible
Hi Алексеев,

Алексеев Сергей wrote:

>Hello team. I got some question/problem with XStream.
> 
>I have a class with custom realization of methods equals/hashCode. Such
> objects contains in HashSet collection. Default XStream behavior: create
> object instance, read attributes, read inner fields, return object and add
> it to collection if needed.
>The problem: due a specific object graph on some step of
>deserialization
> object was created, added to collection, and after all other fields was
> loaded. After fields was loaded, result of hashCode was changed, causing
> "damage" to collection (because HashSet uses HashMap inside). That happens
> because xstream got object with null fields from cache by 'refference'
> attribute. This does not looks like a bug, but working behavior is not
> ideal.

Well, your object graph has circular references and at therefore it is 
simply not possible. At some stage, one of the object cannot be initialized 
fully. XStream behaves even here exactly like Java serialization. Let 
ConnectionPin and Pin both implement Serializable and make the serialization 
algorithm exchangeable:

= %< ===
private static List serializedWithXStream(List inList) 
{
/* toXML  */
XStream xstream = new XStream();
xstream.setMode(XStream.ID_REFERENCES);
xstream.autodetectAnnotations(true);

String serialization = xstream.toXML(inList);
System.out.println(serialization);

/* fromXML  */

System.out.println("\nLoad from xml\n");

List list = (List)xstream.fromXML(serialization);

System.out.println();
return list;
}

private static List 
serializedWithJavaSerialization(List inList) {
try {
/* to bytes  */
ByteArrayOutputStream outputStream = new 
ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outputStream);
oos.writeObject(inList);
oos.close();

/* fromXML  */

System.out.println("\nLoad from bytes\n");

ByteArrayInputStream inputStream = new 
ByteArrayInputStream(outputStream.toByteArray());
ObjectInputStream ois = new ObjectInputStream(inputStream);

List list = (List)ois.readObject();

System.out.println();
return list;
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
= %< ===

If you run your application now calling one time the serialization with 
XStream and one time with Java serialization, you'll see, that you have 
exactly the same problems, because it is simply not possible to have the 
referring and the referred element initialized completely at the same time.

> In my project I fixed it by restoring collection (just recreate it with
> same objects) in readResolve of other object (1 level upward in graph).
>There are other problem: calling readResolve does not guarantee that
>all
> fields of 'this' object (including sub objects in fields) was fully
> deserialized at moment of call. That why I cant fix collection  in
> readResolve of object with HashSet or HashMap and should do it in other
> place.
> 
>There are attach file that nicely describes a situation.

You will have to break the circle for serialization and restore it at 
deserialization time. You may consider readResolve and writeReplace methods 
that actually write/read different replacement objects or play with 
Externalizable or ...

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Unknown field exception

2014-02-19 Thread Jörg Schaible
Hi,

Anjib Mulepati wrote:

> Hi All,
> 
> I have following classes and XML file
> 
> public class CodeCatalog {
>CodeTable codeList;
>//getter and setter
> }
> 
> public class CodeTable {
>private String name;
>private List codeInfoList = new ArrayList();
>//getter and setter
> }
> 
> public class CodeInfo {
>private String code;
>private String name;
>private String description;
>//getter and setter
> }
> 
> 
> 
>   
>  
>123
>Test
>Test code name 1
>  
>  
>456
>Beta
>Test code name 2
>  
>   
> 
> 
> And I have following main class
> 
> public class ConvertApp {
>public static void main(String[] args) {
>  File file = new File("C:\\sampleXML.xml");
>  XStream xstream = new XStream();
>  xstream.alias("codecatalog", CodeCatalog.class);
>  xstream.alias("codetable", CodeTable.class);
>  xstream.alias("codeinfo", CodeInfo.class);
>  xstream.useAttributeFor(CodeTable.class, "name");
>  xstream.addImplicitCollection(CodeTable.class, "codeInfoList");
>  CodeCatalog codeCatalog = (CodeCatalog)xstream.fromXML(file);
>  
System.out.println(codeCatalog.getCodeList().getCodeInfoList().get(1).
> getCode());
>  System.out.println(codeCatalog.getCodeList().getName());
>   }
> }
> 
> I am getting following error
> 
> Exception in thread "main"
> 
com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$U
> nknownFieldException: No such field com.anjib.lab.CodeCatalog.codelist
>  Debugging information 
> field   : codelist
> class   : com.anjib.lab.CodeCatalog
> required-type   : com.anjib.lab.CodeCatalog
> converter-type  :
> com.thoughtworks.xstream.converters.reflection.ReflectionConverter
> path: /codecatalog/codelist
> line number : 3
> version : 1.4.5
> ---
> at
> 
com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.h
> andleUnknownField(AbstractReflectionConverter.java:485)
> at
> 
com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.d
> oUnmarshal(AbstractReflectionConverter.java:341)
> at
> 
com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.u
> nmarshal(AbstractReflectionConverter.java:247)
> at
> 
com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java
> :72)
> at
> 
com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(Abstract
> ReferenceUnmarshaller.java:65)
> at
> 
com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshall
> er.java:66)
> at
> 
com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshall
> er.java:50)
> at
> 
com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:1
> 34)
> at
> 
com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(Abst
> ractTreeMarshallingStrategy.java:32)
> at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1156)
> at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1140)
> at com.thoughtworks.xstream.XStream.fromXML(XStream.java:1104)
> at com.thoughtworks.xstream.XStream.fromXML(XStream.java:1046)
> at com.anjib.lab.ConvertApp.main(ConvertApp.java:17)
> 
> What I am doing wrong?

Your collection is not implicit in the XML. Please read the following 
advice: http://xstream.codehaus.org/faq.html#XML_unmarshalling_fails

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] RE: RE: RE: 1.4 JVM version

2014-02-14 Thread Jörg Schaible
Hi Mica,

Mica Cooper wrote:

> FYI,
> 
> I think by targeting Android, your missing the boat. While clients may use
> Android, I know of zero server platforms using it. The platforms serving
> data, processing, etc will use the older Java, and some still are on 1.1,
> 1.2, and 1.3.
> 
> JDK 1.4.2 had a .19 release not to long ago and JDK.1.4.2.30 for Solaris
> is supported, not EOL.

Well, you two have been the first ones who complained that the current 1.4.x 
version does no longer run OOTB on Java 1.4 ... after 2 years. We had a lot 
more complaints about XStream not running on Android and we got immediately 
feedback, when I broke Android in HEAD some weeks ago.

> Thank you for pointing towards the MAVEN so we can set this up. Appreciate
> the work you do.

Thanks. And as stated on the XStream home page, we'll keep the 1.4.x series 
buildable with Java 1.4.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] RE: RE: 1.4 JVM version

2014-02-14 Thread Jörg Schaible
Hi José & Mica,

Mica Cooper wrote:

> I would second that request.
> 
> Respectfully,
> 
> M. Cooper
>  
> 
> From: Seco Sáiz, José Ramón [mailto:jrs...@indra.es]
> Sent: Friday, February 14, 2014 4:48 AM
> To: user@xstream.codehaus.org
> Subject: [xstream-user] RE: 1.4 JVM version
> 
> Hello,
> 
> First of all, thank you for your wonderful library.
> 
> I do not know if this is the proper way to ask you this (sorry about that)
> but…
> 
> Is it possible to have a version of your last build (1.4.7) compiled for
> the 1.4 JVM?
> 
> I have checked and the 1.3.1 build is fully compatible with 1.4 JVM but
> not the 1.4.7 build.

You may build a version targetting Java 1.4 yourself, this is still 
supported (http://bamboo-ci.codehaus.org/browse/XSTREAM-JDK14). Just use 
Maven 2.0.11 and a 1.4.2 JDK.

There will be no official build though, because unfortunately Android does 
not run Java code targetting the 1.4 platform. So we had to decide to either 
support directly Android or Java 1.4.2. The decision was already made more 
than 2 years ago (http://xstream.codehaus.org/changes.html#1.4.2 - funny 
coincidence) and Java 1.4.2 is now more than 5 years after EOL.

Sorry for the inconvenience,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: preserving the spaces after deserialization

2014-02-11 Thread Jörg Schaible
Hi Nicolas,

Nicolas HERNANDEZ wrote:

> Hi Jörg,
> 
> The spaces are preserved when I serialize using toXML method. When I check
> with an editor I see the original indentation.
> 
> But when I use the following method xstream.fromXML(myXMLString) to
> deserialize,
> all the newlines and tabs characters are replaced by simple whitespaces
> characters.
> 
> Is it more clear ?

No.

 %< ==
 XStream xstream = new XStream();
 String orig = "  abc\n def\n\t\t";
 String xml = xstream.toXML(orig);
 System.out.println(xml);
 if(orig.equals(xstream.fromXML(xml)))
   System.out.println("XML is equal!");
 %< ==

The code above will print 

 %< ==
  abc
 def

XML is equal!
 %< ==

The string has been marshalled into XML and unmarshalled again and its still 
equal.

Cheers,
- Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: preserving the spaces after deserialization

2014-02-11 Thread Jörg Schaible
Hi Nicolas,

Nicolas HERNANDEZ wrote:

> Dear all,
> 
> I would like to preserve the spaces after deserialization.
> 
> I read that the substitution of newlines, tabs characters with spaces
> is part of the XML specification [1].
> I would prefer not to use xml entities as it is suggested.
> 
> I also read that the XML recommendation offers a way to keep these
> characters by using the special attribute xml:space="preserve".
> Unfortunately it seems that no available parser accept it.
> Is there one ? Any other idea by using converters may be ? Do I have to
> implement my own parser ?
> 
> Any suggestion will be welcome.

Sorry, but I don't understand, what you are really up-to. White spaces in 
XML values *are* preserved, because they are part of an objects value. Apart 
from that you get an object (graph) as result and there's no equivalent for 
white spaces between Java objects ... ?!?

Cheers,
- Jörg



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] [ANN][SECURITY] XStream 1.4.7 released

2014-02-08 Thread Jörg Schaible
Hello,

the XStream project is pleased to announce the release of XStream 1.4.7.

The release is primarily a security release to address CVE-2013-7285. XStream 
will no longer handle any java.bean.EventHandler instance as immediate 
consequence. If you know what you do, you may still register the 
ReflectionConverter for this type. Unless you unmarshal such objects, XStream 
1.4.7 is meant as drop-in replacement.

XStream contains now on top of this a security framework, where you can fine-
control any type that is permitted by XStream to unmarshall. All security 
related aspects are described in this new documentation:

 http://xstream.codehaus.org/security.html

Check it out yourself:

 http://xstream.codehaus.org/downloads.html

Enjoy,
XStream Committers


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: Deserialization of JSON into an array of Properties

2014-02-04 Thread Jörg Schaible
Hi Michael,

Michael Minella wrote:

> Jörg,
> 
> Thank you for your insight.  Jettison 1.2 was really the only version I
> had
> not tried but it seems to work with that version (with XStream 1.4.4).

Glad to hear.

> It
> does *not* work with 1.0.1, 1.1, 1.3.3 (the last one was expected). 
> Thanks again!

This seems unfortunately a never ending story. Jettison 1.1.x was as 
incompatible as 1.3.x, Jettison 1.0.x works with Java 1.4, but produces a 
slightly different format and does cover less cases ...

Alas, since we do not control Jettison ... :-/

Cheers,
Jörg

> 
> Michael
> 
> 
> On Tue, Feb 4, 2014 at 4:32 AM, Jörg Schaible
> wrote:
> 
>> Hi Michael,
>>
>> Michael Minella wrote:
>>
>> > I'm running into an issue performing a round trip serializing then
>> > deserializing an object that contains an empty array of Properties. 
>> > I've
>> > created a small test case below that illustrates the issue.  It seems
>> > to work fine when going to XML (using the DomDriver), but not JSON
>> > (using
>> > the JettisonMappedXmlDriver).  Do I need to create a custom converter
>> > for
>> > this, is this a bug, or am I just missing something.  Any insight that
>> can
>> > be provided is appreciated. Thanks in advance!
>>
>> This works for me (the array type does not matter):
>>
>> = %< =
>>  public void testEmptyArray()
>>  {
>>xstream.alias("exception", Exception.class);
>>Exception[] exceptions = new Exception[3];
>>String json = xstream.toXML(exceptions);
>>assertEquals(
>>  "{'exception-array':[{'null':['','','']}]}".replace('\'', '"'),
>>  json);
>>Exception[] exceptions2 = (Exception[])xstream.fromXML(json);
>>assertEquals(json, xstream.toXML(exceptions2));
>>  }
>> = %< =
>>
>> Note, that I am using Jettison 1.2, newer versions are no longer
>> compatible:
>>  - http://xstream.codehaus.org/download.html#optional-deps
>>  - http://xstream.codehaus.org/faq.html#JSON_Jettison_version
>>  - http://jira.codehaus.org/browse/JETTISON-111
>>
>> Remember, XStream writes here into a StAX interface i.e. from its PoV
>> this is plain XML. Jettison is responsible for turning this XML into JSON
>> representation (and vice versa). Therefore you should be aware that you
>> get a different JSON representation if the Properties instance contain
>> one ore more elements (look at the nesting level):
>>
>> = %< =
>>  public void testProperties()
>>  {
>>Properties properties = new Properties();
>>properties.setProperty("key.1", "Value 1");
>>String json = xstream.toXML(properties);
>>assertEquals("{'properties':[{'property':{'@name
>> ':'key.1','@value':'Value
>> 1'}}]}".replace('\'', '"'), json);
>>Properties properties2 = (Properties)xstream.fromXML(json);
>>assertEquals(json, xstream.toXML(properties2));
>>
>>properties.setProperty("key.2", "Value 2");
>>json = xstream.toXML(properties);
>>assertEquals("{'properties':[{'property':
>> [{'@name':'key.2','@value':'Value 2'},{'@name':'key.1','@value':'Value
>> 1'}]}]}".replace('\'', '"'), json);
>>properties2 = (Properties)xstream.fromXML(json);
>>assertEquals(json, xstream.toXML(properties2));
>>  }
>> = %< =
>>
>> You get best results with simple objects and plain lists/arrays, the
>> conversion to and from JSON *is* limited, see word of warning:
>>
>>  - http://xstream.codehaus.org/json-tutorial.html
>>
>> Cheers,
>> Jörg
>>
>>
>> -
>> To unsubscribe from this list, please visit:
>>
>> http://xircles.codehaus.org/manage_email
>>
>>
>>



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Deserialization of JSON into an array of Properties

2014-02-04 Thread Jörg Schaible
Hi Michael,

Michael Minella wrote:

> I'm running into an issue performing a round trip serializing then
> deserializing an object that contains an empty array of Properties.  I've
> created a small test case below that illustrates the issue.  It seems to
> work fine when going to XML (using the DomDriver), but not JSON (using
> the JettisonMappedXmlDriver).  Do I need to create a custom converter for
> this, is this a bug, or am I just missing something.  Any insight that can
> be provided is appreciated. Thanks in advance!

This works for me (the array type does not matter):

= %< =
 public void testEmptyArray()
 {
   xstream.alias("exception", Exception.class);
   Exception[] exceptions = new Exception[3];
   String json = xstream.toXML(exceptions);
   assertEquals(
 "{'exception-array':[{'null':['','','']}]}".replace('\'', '"'),
 json);
   Exception[] exceptions2 = (Exception[])xstream.fromXML(json);
   assertEquals(json, xstream.toXML(exceptions2));
 }
= %< =

Note, that I am using Jettison 1.2, newer versions are no longer compatible:
 - http://xstream.codehaus.org/download.html#optional-deps
 - http://xstream.codehaus.org/faq.html#JSON_Jettison_version
 - http://jira.codehaus.org/browse/JETTISON-111

Remember, XStream writes here into a StAX interface i.e. from its PoV this 
is plain XML. Jettison is responsible for turning this XML into JSON 
representation (and vice versa). Therefore you should be aware that you get 
a different JSON representation if the Properties instance contain one ore 
more elements (look at the nesting level):

= %< =
 public void testProperties()
 {
   Properties properties = new Properties();
   properties.setProperty("key.1", "Value 1");
   String json = xstream.toXML(properties);
   assertEquals("{'properties':[{'property':{'@name':'key.1','@value':'Value 
1'}}]}".replace('\'', '"'), json);
   Properties properties2 = (Properties)xstream.fromXML(json);
   assertEquals(json, xstream.toXML(properties2));

   properties.setProperty("key.2", "Value 2");
   json = xstream.toXML(properties);
   assertEquals("{'properties':[{'property':
[{'@name':'key.2','@value':'Value 2'},{'@name':'key.1','@value':'Value 
1'}]}]}".replace('\'', '"'), json);
   properties2 = (Properties)xstream.fromXML(json);
   assertEquals(json, xstream.toXML(properties2));
 }
= %< =

You get best results with simple objects and plain lists/arrays, the 
conversion to and from JSON *is* limited, see word of warning:

 - http://xstream.codehaus.org/json-tutorial.html

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Alternative converter invocation when previous's call failed

2014-02-03 Thread Jörg Schaible
Hi Pawel,

Kowalski, Pawel wrote:

> 
> Hi,
> 
> I have plenty of data (joda DateTime objects) serialized with default
> (ReflectionConverter) now I'd like to simplify serialization and created
> my own Converter for these  objects. The issue is I'd like to have
> possibility to support both versions at the same time as there is no
> possibility to convert already exiting records. What I'm trying to do is
> simply create new converter that will work more or less like following:
> 
> Try to unmarshall in new version
> If failed
> Do something to call another converter (in my case
> Reflection Converter)???
> 
> Is there possibility to manage above with existing XStream API? I mean is
> there any way like throwing some exception to call alternative converter
> once previous failed, or should I register converters in some specific
> way?

No.

> How to get access to one converter from another? How to reset the reader
> to point the same element as it was primary called with (once data read
> multiple times moveDown/moveUp etc. and then  failed)?

Actually this last question is the problem, why it cannot work this way. 
XStream is stream-based and relies on the underlaying XML parser. There is 
no possibility to reset the individual parsers to a specific mark nor can 
you control the input stream because the parsers also use different caching 
mechanisms i.e. you never know how many of the read bytes have actually been 
processed by the XML parser.

The best option is to use a version attribute in your root element:

== %< 
 
[...]
 
== %< 

Derive from the converter that will normally handle this element and get the 
version in the unmarshal method:

== %< 
  public Object unmarshal(HierarchicalStreamReader reader, 
UnmarshallingContext context) {
String version = reader.getAttribute("version");
context.put("version", version == null ? "1" : version);
return super.unmarshal(reader, context);
  }
== %< 

Now you take a similar approach for the Joda-Time types you want to handle. 
Simply derive from the converter that handled the type in the last version 
(assuming ReflectionConverter for now):

== %< 
  class JodaTimeTypeConverter extends ReflectionConverter {
public JodaTimeTypeConverter(Mapper mapper, ReflectionProvider 
reflectionProvider) {
  super(mapper, reflectionProvider);
}
boolean canConvert(Class type) {
  return ;
}
public void marshal(Object source, HierarchicalStreamWriter writer, 
MarshallingContext context) {
  // your implementation for the new representation
}
public Object unmarshal(HierarchicalStreamReader reader, 
UnmarshallingContext context) {
  String version = content.get("version");
  if ("1".equals(version)) { // old format
return super.unmarshal(reader, context);
  } else {
// your implementation for the new representation
  }
}
}
== %< 

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: NPE with @XStreamAsAttribute annotation on generics during serialization

2014-01-29 Thread Jörg Schaible
Hi Andreas,

Zschorn, Andreas wrote:

> Hi guys,
> 
> We are using xstream quite heavily and  have an surprising blocker, while
> updating from xstream 1.3.1 to 1.4.6 in order to make our application java
> 7 ready.
> 
> The annotation @XStreamAsAttribute does not work with generics anymore, it
> results in an NPE during serialization to XML. It was working with 1.3.1
> 
> 
com.thoughtworks.xstream.converters.reflection.SerializationMethodInvoker.getMethod(SerializationMethodInvoker.java:161)
> 
> Has anyone experienced something similar, or knows an workaround.
> I could not find anything in jira.
> I created an ticket for it and attached an example project with testcases.
> 
> http://jira.codehaus.org/browse/XSTR-753
> This is an quite big blocker for us. Does anyone has an hint, what is
> going wrong.

It works for normal generic parameters, but not for bounded ones, I'll have 
to investigate. However, the field cannot be written as attribute anymore!

See:

=== %< 
 class X {
   @XStreamAsAttribute
   String s;
 }
 X x = new X();
 x.s="value";
 system.out.println(new XStream().toXML(x));
=== %< 

this will be written as:

=== %< 
 
=== %< 

However, it is different for this class:

=== %< 
 class Y {
   @XStreamAsAttribute
   T s;
 }
 Y y = new Y();
 y.s="value";
 system.out.println(new XStream().toXML(y));
=== %< 

XML will be written as:

=== %< 
 
   value
 
=== %< 

The class contains an Object as field type as a result of the type erasure. 
Since type of the instance does not match type of the field, no attribute 
can be generated for the field. You will have to write a custom converter.

I will have to take a closer look though, why this NPE occurs if the generic 
parameter type is bounded. Stay tuned.

Regards,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: weird problems deserializing

2014-01-25 Thread Jörg Schaible
Hi Jason,

Jason Novotny wrote:

> Hi,
> 
> I'm having an extreely strange problem where I run a unit test on my Mac
> that works fine but the identical code on a linux server produces an
> xstream related error:
> 
> 
> testInrixAuthentication(.service.inrix.InrixServiceTest): Could not
> read [class .service.inrix.auth.InrixGetSecurityTokenResponse];
> nested exception is
> org.springframework.oxm.UnmarshallingFailureException: XStream
> unmarshalling exception; nested exception is
> com.thoughtworks.xstream.mapper.CannotResolveClassException: Inrix

This simply tells you, that XStream cannot find any class named "Inrix" in 
the default package.

> Basically I'm trying to serialize the XML into an Object and was using
> annotations so the class looks like:
> 
> @XStreamAlias("Inrix")
> public class InrixGetSecurityTokenResponse {
> 
> @XStreamAlias("AuthResponse")
> private InrixAuthResponse authResponse;
> 
> public InrixAuthResponse getAuthResponse() {
> return authResponse;
> }
> 
> public void setAuthResponse(InrixAuthResponse authResponse) {
> this.authResponse = authResponse;
> }
> 
> }

It depends how your XStream was set up. By default, at deserialization time, 
XStream simple gets an XML element "Inrix" - how should it know, that 
there's somewhere a class with an alias annotation?

> I just can't understand why it works on one machine but not another-- I
> do understand that in using maven to build, the class listed above is
> contained in my project jar file, while the test that calls it lives in
> test-classes directory, so maybe there is some issue with the
> classloader of the test class needing the classloader of the jar
> containing my annotated POJOs, but this doesn't seem to explain why it
> works on one machine but not the other
> 
> Any ideas on debugging this would be greatly helpful!

Anything is explained here:
http://xstream.codehaus.org/annotations-tutorial.html#AutoDetect

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: Xstream - order of attribute

2014-01-22 Thread Jörg Schaible
Hi Márk

Márk Pásztor wrote:

> Hello,
> 
> Sorry i frogot to mension this problem is affect when I use converter.
> When unmarshall method calling i try to get the attributes and i got this
> in bad order.
> I use XppDomDriver because the default XppDriver doesn't work well with
> attributes (or i made something's wrong).
> Sorry for my bad english.
> 
> 
> 
> *for(int i = 0; i < reader.getAttributeCount(); i++){
> element.getAttributes().add(new Attribute(reader.getAttributeName(i),
> reader.getAttribute(i)));}*
> 
> Thanks for your help!

Sorry, but when I look at this code, I have the simple impression, that 
there's a basic misunderstanding about what XStream does or how it works.

Looking at your XML, I'd expected something along:

=== %< =
 class Test { String a; String b; double c; double d };
 
 Test test = new Test;
 test.a = "w";
 test.b = "I";
 test.c = 553.0;
 test.d = 1.0;

 XStream xstream = new XStream();
 xstream.alias("test", Test.class);
 xstream.useAttributeFor(String.class);
 xstream.useAttributeFor(double.class);
 String xml = xstream.toXML(test);
 System.oout.println("OUTPUT:"+xml);
 Test copy = (Test)xstream.fromXML(xml);
=== %< =====

What does your converter and why is it using an XppDom structure?

- Jörg

> 
> 
> 
> 2014/1/21 Jörg Schaible 
> 
>> Hi Márk,
>>
>> Márk Pásztor wrote:
>>
>> > Hello everybody,
>> >
>> > I use xstream for a year. It's work very well.
>> > But now I got a problem. I would like to write an xml file from an
>> > input xml file.
>> > And I would like to preserve the order of input attributes to the
>> > output file.
>> >
>> > Now looks like this:
>> >
>> >
>> >
>> > *INPUT:OUTPUT:> > d="1.0" c="553.0"/>*
>> >
>> > Expected result:
>> >
>> >
>> >
>> > *INPUT:OUTPUT:> > c="553.0" d="1.0"/>*
>> >
>> > What can I do in this case? Do you have any ideas?
>>
>> XStream writes attributes normally in declaration order of the Java type.
>>
>> Cheers,
>> Jörg
>>
>>
>> -
>> To unsubscribe from this list, please visit:
>>
>> http://xircles.codehaus.org/manage_email
>>
>>
>>
> 
> 



-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Xstream - order of attribute

2014-01-21 Thread Jörg Schaible
Hi Márk,

Márk Pásztor wrote:

> Hello everybody,
> 
> I use xstream for a year. It's work very well.
> But now I got a problem. I would like to write an xml file from an input
> xml file.
> And I would like to preserve the order of input attributes to the output
> file.
> 
> Now looks like this:
> 
> 
> 
> *INPUT:OUTPUT: d="1.0" c="553.0"/>*
> 
> Expected result:
> 
> 
> 
> *INPUT:OUTPUT: c="553.0" d="1.0"/>*
> 
> What can I do in this case? Do you have any ideas?

XStream writes attributes normally in declaration order of the Java type.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: Re: DataHolder

2014-01-18 Thread Jörg Schaible
Hi Uwe,

u...@codesmell.de wrote:

> On 01/18/2014 06:51 PM, u...@codesmell.de wrote:
>> it works nicely with calling mashall/unmarshall myself, providing a
>> custom DataHolder. the only inconvenience is, that - calling
>> unmarshall - i need to know what the root-type is.
> PS: i just realized i could just pass null as the root object, so the
> above statement is plain wrong.

Yes, that argument is only required if you absolutely want to fill an 
existing object.

> sorry, uwe

No problem,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




[xstream-user] Re: DataHolder

2014-01-18 Thread Jörg Schaible
Hi Uwe,

u...@codesmell.de wrote:

> Hi
> 
> i am trying to use the DataHolder interface to record information on
> marshalling and add info on unmarshalling using a custom converter.
> 
> while this works if i use XStream.marshall/unmarshall methods, i get
> NPEs if i use fromXML/toXML on the same xstream instance.
> 
> i *thought* (that might be my misconception) that newDataHolder() was
> called during toXML to create an initial DataHolder to be passed to the
> converters.
> 
> according to my eclipse and my debug-output, XStream.newDataHolder is
> never called.
> Am i right and this is a bug, or what do i miss ?
> 
> is there another way of getting grips of the DataHolder being used on
> unmarshalling, so that i can provider the info to it which is needed by
> my converter?
> 
> XStream version is 1.4.5/6

I am not sure, what you really want to do. The DataHolder that is used by 
default is created for every call to marshal/unmarshal so that the 
converters may communicate within one (un)marshalling process.

If you provide a DataHolder yourself, you define how long this data is kept.

XStream.newDataHolder is a convenience method for *you* to provide an own 
one, XStream does not call it.

Cheers,
Jörg


-
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email




  1   2   3   4   >