How can I tweek Xstream to handle XML to Java objects that include attributes and values? - xml-serialization

For example, how would form an object from XML written like this?
<name length="4">Ryan</name>
I would normally alias a class using an annotation to "name" and then have a length and a field for the name. However, this will not work because the second field has no name.
*Edit confusing wording

It has been a while since I used xstream (2+ years) but I do remember using converters to change the way that objects are serialized. Check out http://x-stream.github.io/converters.html. Also this tutorial, http://x-stream.github.io/converter-tutorial.html, has some examples with attributes down towards the bottom.

Why not use JAXB?
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
#XmlRootElement
public class Name {
#XmlValue
private String name;
#XmlAttribute
private int length;
}

Related

HTL Access Property Without Getter

I'm writing an AEM component and I have an object being returned that is a type from an SDK. This type has public properties and no getters. For simplicity, it might be defined like this:
class MyItem {
public String prop1;
public String prop2;
}
Now normally, I would need a getter, like so:
class MyItem {
public String prop1;
public String prop2;
public String getProp1() {
return prop1;
}
}
But I do not have this luxury. Right now, I've got a Java implementation that uses another type to resolve this, but I think it's sort of crazy that HTL doesn't allow me to just access prop1 directly (it calls the getter). I've reviewed the documentation and can't see any indication of how this could be done. I'd like to be able to write:
${item.prop1}
And have it access the public property instead of calling getProp1().
Is this possible?
You don't need getters for public fields if those fields were declared by your Java Use-class. There's actually a test in Apache Sling that covers this scenario:
https://github.com/apache/sling/blob/trunk/bundles/scripting/sightly/testing-content/src/main/resources/SLING-INF/apps/sightly/scripts/use/repopojo.html
This also applies to Use-classes exported from bundles.
For Sling Models using the adapter pattern [0] I've created https://issues.apache.org/jira/browse/SLING-7075.
[0] - https://sling.apache.org/documentation/bundles/models.html#specifying-an-alternate-adapter-class-since-110
From the official documentation
Once the use-class has initialized, the HTL file is run. During this stage HTL will typically pull in the state of various member variables of the use-class and render them for presentation.
To provide access to these values from within the HTL file you must define custom getter methods in the use-class according to the following naming convention:
A method of the form getXyz will expose within the HTL file an object property called xyz.
For example, in the following example, the methods getTitle and getDescription result in the object properties title and description becoming accessible within the context of the HTL file:
The HTL parser does enumerate all the public properties just like any java enumeration of public fuields which include getters and public memebers.
Although it is questionable on whether you should have public variable but thats not part of this discussion. In essence ot should work as pointed by others.

Using #Id on methods

I would like to annotate a method with Spring Data #Id but it only works with fields, despite the fact that the annotation can be used on methods.
Is there a way to use #Id on methods too?
I'm using Spring Boot 1.3.0.RELEASE
EDIT
Actually I have this interface that will have an instance being created at runtime.
import org.springframework.data.annotation.Id;
#Document(indexName = "index", type = "document")
public interface Document {
#Id
Integer getId();
}
And this repository.
public interface DocumentRepository extends ElasticsearchCrudRepository<Document, Integer> {
}
Problem is that SimpleElasticsearchPersistentProperty from spring-data-elasticsearch 1.3.0.RELEASE always look for fields:
https://github.com/spring-projects/spring-data-elasticsearch/blob/1.3.0.RELEASE/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentProperty.java
That way if I create an asbtract class instead and put #Id on a field, everything works fine.
The #Id annotation does work on properties, i.e. you can put it on getters, setters or fields. If this does not work something is wrong. Possible reasons are:
the names don't fit the property conventions
you are using the wrong #Id annotation
It does not work on arbitrary methods because Spring Data wouldn't be able to determine a name for that non-property, which in turn is required for many features.

Is it possible to specify a property naming strategy with an annotation?

I have a class defined as:
class Person {
public int age;
public String firstName;
}
Note that I use camel case for the field names. Also, I know that I could have generated getters and setters but I tend to not do that for simple domain objects.
When I deserialize a JSON or XML response in my REST API, it should spit out:
<Person><Age>11</Age><FirstName>Johnson</FirstName></Person>
You will notice that the first letter is upper-cased.
I could use, for example, #JsonPoperty("FirstName") on my POJO to get the output the way I need it, but this doesn't scale when there are too many fields. I'd like to use a custom property naming strategy (as described in How To Use Property Naming Strategy In Jackson). But instead of configuring an ObjectMapper, I was wondering if its possible to specify a naming strategy using annotations?
Thanks

EXT GWT BaseModel needs to have DTO reference?

I am very new to GWT.
I am using ext-gwt widgets.
I found many places in my office code containing like,
class A extends BaseModel{
private UserAccountDetailsDto userAccountDetailsDto = null;
//SETTER & GETTER IN BASEMODEL WAY
}
Also, the DTO reference is unused.
public class UserAccountDetailsDto implements Serializable{
private Long userId=null;
private String userName=null;
private String userAccount=null;
private String userPermissions=null;
//NORMAL SETTER & GETTER
}
Now, I am able to get the result from GWT Server side Code and things Work fine, but when I comment the DTO reference inside the class A, I am not getting any Result.
Please explain me the need of that.
Thanks
Well the problem is in implementation of GXT BaseModel and GWT-RPC serialization.
BaseModel is based around special GXT map, RpcMap. This map has defined special serialization rules, which let's avoid RPC type explosion, but as side effect, only some simple types stored in map will be serialized. E.g. you can put any type inside the map, but if you serialize/deserialize it, only values of type Integer, String ,Double,Byte, Float and Short (and arrays of this types) will be present. So the meaning behind putting reference to the DTO inside BaseModel, is to tell GWT-RPC that this type is also have to be serialized.
Detailed explanation
Basically GWT-RPC works like this:
When you define an interface for service, GWT-RPC analyzes all the classes used in parameters/ return type, to create serializers/deserializers. If you return something like Map<Object,Object> from your service, GWT-RPC will have to create a serializer for each class which implements Map and Serializable interfaces, but also it will generate serializers for each class which implements Serializable. In the end it is quite a bad situation, because the size of your compiled js file will be much biggger. This situation is called GWT-RPC type explosion.
So, in the BaseModel, all values are stored in RpcMap. And RpcMap has custom written serializer (RpcMap_CustomFieldSerializer you can see it's code if you interested how to create such things), so it doesn't cause the problem described above. But since it has custom serializer GWT dosn't know which custom class have been put inside RpcMap, and it doesn't generate serializers for them. So when you put some field into your BaseModel class, gwt knows that it might need to be able to serialize this class, so it will generate all the required stuff for this class.
Porting GXT2 Application code using BaseModel to GXT3 Model is uphill task. It would be more or less completely rewrite on model side with ModelProviders from GXT3 providing some flexibility. Any code that relies on Model's events, store, record etc are in for a rewrite.

Form validation in Play 2.0

OK, So I am having some issues with getting data from a form to bind to a model class I have.
I have a class Question that basically looks like this:
#Entity
public class Question extends Model {
#Id #Required public int id;
public String title;
public String body;
...methods...
}
So I want to use this as a template for a form for a user to create a question, so I create a static instance (as they do in the samples)
final static Form<Question> question_form = form(Question.class);
So far so good, everything compiles. The problem comes when I actually submit the form:
Form<Question> filled_form = new Form<Question>(Question.class).bindFromRequest();
Here I get the error:
[UnexpectedTypeException: No validator could be found for type: java.lang.Integer]
My thinking on how to proceed is to use a design pattern that goes like this:
1.) Create template classes specifically for Forms, that don't include things like foreign keys, IDs, and information that isn't in a format designed for the user. (i.e. if the Question has a foreign key for Topic, the QuestionForm class would have a String topic field.
2.) Create a methods in the Question model that goes something like getFormForQuestion(Question) and getQuestionForForm(Form<Question>) and then use these methods to do CRUD functions.
So basically the User and controller interact using Forms, and then the Model knows how to take these forms and turn them into entries in the database.
Is this a reasonable way to proceed? Or is there a better way of doing this?
UPDATE:
Seems to be fixed when using #GeneratedValue annotation rather than the #Required annotation, but I am still curious regarding my proposed Form Design pattern.
Also just removing #Required appears to fix the problems. Still looking for comments on the mentioned design pattern!
id field doesn't need any validation, ORM will care about it. Of course you should not place id in form (it shouldn't be edited at all - it's common AUTO_INCREMENT) And better make it Long, just:
#Id
public Long id;