Castor Marshaller to return empty tags for null objects - object

We are using Castor to unmarshall the Castor object to XML string. Castor is not generating Empty tags for null objects. Is there a API available to set it as parameter while unmarshalling?
There is a way to handle it by using the handler and override convertUponGet method to return empty string. But, Is there a better to do it?
Any clues will help.

From what I have seen there are 3 ways of dealing with this in order of best to worst.
Use a GeneralizedFieldHandler as explained in http://stackoverflow.com/questions/9176479/how-to-tell-castor-to-marshall-a-null-field-to-an-empty-tag. The field handler is reusable for other fields and doesn't change the behavior of your class.
Modify your get method for the given field to check for nulls and return an empty string if it is null. This approach changes the behavior of your class so if you have other parts of your code relying on nulls for this field, which also isn't a good idea, you will run into problems.
Modify Castor yourself to return an empty string when a null is encountered. Usually a really bad idea changing a tool you are using, unless you submit it back to the developers of the project to integrate into their code base for future releases. This doesn't seem likely since this issue was brought up back in 2007 http://old.nabble.com/Forcing-marshalling-of-null-empty-values--to9080721.html#a9096375 if not earlier

Related

Xpages Null or empty string

I am working with xpages components and it is hard for me to quess when the getComponent("comp").getValue() returns null or when returns "" (empty string).
Is there a way to tell? Are there components which return null when other components return ""?
A component will have a null value if the value property has not been assigned. That can happen if the it's bound to a field on a document and that document does not yet have the field, e.g. it's a brand new document. It can also happen if it's bound to a scoped variable that hasn't been set yet.
It's best practice to bind, wherever possible, to the data source rather than go via the component. This way document1.getItemValueString("myField") will return a blank string if myField hasn't been set on document1, as well as if myField's value is "". Also, if in the future youo delete the component comp, the compiler won't (and can't) tell you you're calling that component in SSJS and you'll get a runtime error. If you're using document1.getItemValueString("myField"), it will still work.
Plus, as Tim Tripcony said, it's slower https://twitter.com/timtripcony/status/359532216382001152 and this blog post goes into much greater depth on why to talk to data not components http://www.timtripcony.com/blog.nsf/d6plinks/TTRY-942UPQ

Can i get all components of an xsp document in xpages?

I have a simple document with 3 fields and 1 rich text field. I also have an xpage with 3 simple edit box controls and 1 rich text. The name of my NotesXSPDocument is document1.
Question 1:
Can i get a vector with all the controls of the xsp document? for example, instead of using getComponent("fld1"), getComponent("fld2") ... etc, can i use something like getAllComponents() or document1.getControls()? These methods do not exist of course so i am asking if there is a way to do it. I know i can get all items of a document (not XSP) by calling document1.getDocument().getItems(). IS there anything similar for xsp?
Question2:
Lets say we can get a vector as i described above. Then if i iterate through this vector to get each control's value, is there a method to check if it is rich text or simple text field?
Technically, yes, but not readily and this is one of those situations where there's likely a better way to approach whatever underlying problem it is you want to solve.
Nonetheless, if you're looking to get a list of inputs on the page, XspQuery is your friend: http://avatar.red-pill.mobi/tim/blog.nsf/d6plinks/TTRY-96R5ZT . With that, you could use "locateInputs" to get a List of all the inputs on the page, and then check their value method bindings to see if the string version is referencing your variable name. Error-prone and not pretty, but it'd work. Since they're property bindings, I don't think the startsWith filter in there would do what you want.
Alternatively, you could bind the components to something in a Java class from the start. I've been doing just such a thing recently (for a different end) and initially described it here: https://frostillic.us/f.nsf/posts/my-black-magic-for-the-day . The upshot is that, with the right cleverness for how you do your binding="" property, you could get a list of all the components that reference a property of a given object.
As for the second part of the question, if you DO get a handle on the components one way or another, you can check to see if it's a rich text control by doing "component instanceof com.ibm.xsp.UIInputRichText".
A bit complex but yes. facesContext.getViewRoot() is an UIViewRoot object so it has List<UIComponent> getChildren() method which returns its children.
However, since it's a tree-structure, some of its children will have additional children components. You have to traverse the entire tree to build a list of components you want to see.
For types, you can decide what type a component is by its class. For instance, UIInput is a text box, etc.

Preventing StackOverflowException while serializing Entity Framework object graph into Json

I want to serialize an Entity Framework Self-Tracking Entities full object graph (parent + children in one to many relationships) into Json.
For serializing I use ServiceStack.JsonSerializer.
This is how my database looks like (for simplicity, I dropped all irrelevant fields):
I fetch a full profile graph in this way:
public Profile GetUserProfile(Guid userID)
{
using (var db = new AcmeEntities())
{
return db.Profiles.Include("ProfileImages").Single(p => p.UserId == userId);
}
}
The problem is that attempting to serialize it:
Profile profile = GetUserProfile(userId);
ServiceStack.JsonSerializer.SerializeToString(profile);
produces a StackOverflowException.
I believe that this is because EF provides an infinite model that screws the serializer up. That is, I can techincally call: profile.ProfileImages[0].Profile.ProfileImages[0].Profile ... and so on.
How can I "flatten" my EF object graph or otherwise prevent ServiceStack.JsonSerializer from running into stack overflow situation?
Note: I don't want to project my object into an anonymous type (like these suggestions) because that would introduce a very long and hard-to-maintain fragment of code).
You have conflicting concerns, the EF model is optimized for storing your data model in an RDBMS, and not for serialization - which is what role having separate DTOs would play. Otherwise your clients will be binded to your Database where every change on your data model has the potential to break your existing service clients.
With that said, the right thing to do would be to maintain separate DTOs that you map to which defines the desired shape (aka wireformat) that you want the models to look like from the outside world.
ServiceStack.Common includes built-in mapping functions (i.e. TranslateTo/PopulateFrom) that simplifies mapping entities to DTOs and vice-versa. Here's an example showing this:
https://groups.google.com/d/msg/servicestack/BF-egdVm3M8/0DXLIeDoVJEJ
The alternative is to decorate the fields you want to serialize on your Data Model with [DataContract] / [DataMember] fields. Any properties not attributed with [DataMember] wont be serialized - so you would use this to hide the cyclical references which are causing the StackOverflowException.
For the sake of my fellow StackOverflowers that get into this question, I'll explain what I eventually did:
In the case I described, you have to use the standard .NET serializer (rather than ServiceStack's): System.Web.Script.Serialization.JavaScriptSerializer. The reason is that you can decorate navigation properties you don't want the serializer to handle in a [ScriptIgnore] attribute.
By the way, you can still use ServiceStack.JsonSerializer for deserializing - it's faster than .NET's and you don't have the StackOverflowException issues I asked this question about.
The other problem is how to get the Self-Tracking Entities to decorate relevant navigation properties with [ScriptIgnore].
Explanation: Without [ScriptIgnore], serializing (using .NET Javascript serializer) will also raise an exception, about circular
references (similar to the issue that raises StackOverflowException in
ServiceStack). We need to eliminate the circularity, and this is done
using [ScriptIgnore].
So I edited the .TT file that came with ADO.NET Self-Tracking Entity Generator Template and set it to contain [ScriptIgnore] in relevant places (if someone will want the code diff, write me a comment). Some say that it's a bad practice to edit these "external", not-meant-to-be-edited files, but heck - it solves the problem, and it's the only way that doesn't force me to re-architect my whole application (use POCOs instead of STEs, use DTOs for everything etc.)
#mythz: I don't absolutely agree with your argue about using DTOs - see me comments to your answer. I really appreciate your enormous efforts building ServiceStack (all of the modules!) and making it free to use and open-source. I just encourage you to either respect [ScriptIgnore] attribute in your text serializers or come up with an attribute of yours. Else, even if one actually can use DTOs, they can't add navigation properties from a child object back to a parent one because they'll get a StackOverflowException.
I do mark your answer as "accepted" because after all, it helped me finding my way in this issue.
Be sure to Detach entity from ObjectContext before Serializing it.
I also used Newton JsonSerializer.
JsonConvert.SerializeObject(EntityObject, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });

Can we get declared properties of a Groovy class by its order?

I created a plain Groovy class (i.e Person class)with some properties. Now I want to get those declared attributes (which I've defined in my class) with their order, but I don't know how to do it.
I've tried to use Person.metaClass.getProperties() but it retrieves not only declared properties but also built-in Groovy ones.
Could you please help me on this: just get declared properties by its order when declaring.
Thank you so much!
I can't see a use case, but the compiler could reorder all fields declaration while creating bytecode. I'm pretty sure ordering is not a constraint on fields though it should mostly be the case for not modified/enhanced class
As per the JVM spec, generated fields should be marked SYNTHETIC (like generated methods) in the bytecode, so you can test with :
Person.getDeclaredFields().grep { !it.synthetic }
and filter the base Groovy fields like ClassInfo,metaClass and others beginning by __timestamp
But I'm not a specialist, there could be another way I don't think of
There was a question about this on the mailing list back in February of this year
The answer is, no. There is no way to get properties in the order they are declared in the class without doing some extra work.
You could parse the source file for the class, and generate an ordered list of property names from that
You could write a custom annotation, and annotate the fields with this annotation ie: #Order(1) String prop
You could make all of the classes where this matters implement an interface which forces them to have a method that returns the names of the properties in order.
Other than that, you probably want to have a re-think :-(

JSF: How do I include parameters in an action method's return string?

I'm writing an action method that will store a new object in a database. Once this is done, I want to navigate to view that newly created object. To do this, I was planning to include a querystring or some sort of parameter in the return String of the action method, but I can't figure out how. If I append a query string manually, it appears that it's being ignored. Also, manually adding parameters by concatenating strings doesn't seem like a good idea to me. Is it possible to do this in a type-safe manner?
The way I've always handled this is to get a reference to the bean which provides the content for the page you'll be displaying, and just set its properties directly. The navigation string returned from an action method isn't meant for passing parameters, but you don't need it to; all they'd be used for is setting bean properties anyway.

Resources