Simplest way to use composed object as RequestParam in Spring - spring-mvc

To following is something like... pseudo code... To illustrate what I am looking for:
// Setters and Getters ommitted to keep the example short here:
class Address
{
private String street;
private String city;
}
class AddressBookEntry
{
private String name;
private Address address;
}
class MyController
{
public void render(#RenderParam AddressBookEntry entry)
{
...
}
}
As you can see there are two POJOs (Address and AddressBookEntry). Now I would like to pass an AddressBookEntry to my Controller as http request parameter. I imagine that the URL looks like this: /target?entry.name=Random-Guy&entry.address.street=Random-Street&entry.address.city=Random-City.
As far as I understand #RenderParam doesn't work this way. I would have to create a PropertyEditor that takes a single string and construct my target Object from it, which means that I can't have an individual URL-param for each (sub-)property.
#ModelAttribute comes closer, but I could not find any hint if and how nesting of objects might work with this annotation. Additionally this annotation works without the "entry." prefix in my URL above which means that I need to make sure that I don't have multiple ModelAttributes that share a property name, correct? That sounds stressful.
How can I solve this?

It's the situation when you should use #ModelAttribute. It supports nested objects as you want.
If you need multiple #ModelAttributes, you can compose them into special class (for example, it you case that class can contain a field named entry of type AddressBookEntry, so that parameter names will be the same).

Related

Unique constraint at field in collection

is it possible to make this validation:
class Man {
#Unique
String name;
}
class Order {
#Valid
List<Man> manCollection;
}
where is unique logic is: every item in collection manCollection is unique.
You could make this snippet ambiguous just by adding a Customer class that contains a List of Orders:
class Man {
#Unique
String name;
}
class Order {
#Valid
List<Man> manCollection;
}
class Customer {
#Valid
List<Order> orderCollection;
}
Then one couldn't possibly know whether the Man objects must be unique within a given Order or within a given Customer (or both).
So I don't think it's possible with this exact syntax, regardless of what the Bean Validation APIs allow.
What you could do is move the annotation to manCollection, e.g. #UniqueMen List<Man> manCollection;, and implement a ConstraintValidator<List<Man>>.
If it's useful to you, you could even make a more generic #UniqueContent annotation, but that would be much more complex. You would need to pass the target type as a parameter (#UniqueContent(target = Man.class)) and write a validator that parses annotations on the target class in its initialize method. Be careful to use some caching mechanism, though, because annotation parsing is quite slow.

Example of how to add secondary index when storing object in Riak with Java Client?

I am storing a hash-map in a riak bucket like this:
bucket.store(key, docHashMap).execute();
I would like to store the object with a secondary index.
How would I accomplish this? I am aware that the IRiakObject has a addIndex method, but how do I access the IRiakObject before it is stored?
I would think that what I am trying to do is the expected use-case, yet I am not able to find any documentation or examples on this. If you can point me to one that would be greatly appreciated.
Thanks!
Update:
#Brian Roach answered this on the Riak mailing list and below. Here is the custom class that I wrote that extends the HashMap:
class DocMap extends HashMap<String, Object> {
/**
* Generated id
*/
private static final long serialVersionUID = 5807773481499313384L;
#RiakIndex(name="status") private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
I can still use the object as an ordinary hashmap and store keys and values, but it will also write "status" to a secondary index (and actually end up being called "status_bin" since it's a string.
If you're just passing in an instance of the core Java HashMap ... you can't.
The way the default JSONConverter works for metadata (such as indexes)
is via annotations.
The object being passed in needs to have a field annotated with
#RiakIndex("index_name"). That field can be a Long/Set<Long> or
String/Set<String> (for _int and _bin indexes respectively).
These are not converted to JSON so they won't affect your serialized
data. You can have multiple fields for multiple indexes.
You don't have to append "_int" or "_bin" to the index name in the
annotation - it's done automatically based on the type.
Easiest thing to do woud be to extend HashMap and simply add the
annotated field(s).

ASP.net how to extend a control or collection

I am attempting to extend a List. When using Visual Studio there are the different code hints for all the functions I can use with a List object. How can I extend the functionality of the List to show my new function?
public class ListExtensionHelper<T> : System.Collections.Generic.List<T>
{
public List<T> AwesomeFunction<T>()
{
}
}
For the life of me I could not find anything online on how I would do it for a List
If you are trying to add AwesomeFunction as an extension method to a regular List object, then you need to define an extension method in a static class:
public static class ListExtensions
{
public static List<T> AwesomeFunction<T>(this List<T> list)
{
}
}
Otherwise, the code you have should work; if you instantiate the ListExtensionHelper class, it should have all the functions of List as well as AwesomeFunction.
It sounds like you're looking for extension methods, rather than inheritance.
There are some really good examples here. There's also a really good library of extensions available here.
<soapbox>
One of my personal favorites that I use is this:
public static class StringExtensions
{
public static bool IsNullOrEmpty(this string s)
{
return string.IsNullOrEmpty(s);
}
}
It's ridiculously simple, but a huge pet peeve of mine is having to write:
if (string.IsNullOrEmpty(someVariable))
as opposed to:
if (someVariable.IsNullOrEmpty())
For me it's just a matter of being a natural construct of my native language. The built-in method sounds like:
object verb subject
whereas mine sounds like:
subject verb
It's probably silly, but when I want to act upon a subject it just makes more sense for me to start with the subject :)
</soapbox>

Grails data binding

I need to bind request parameters to an instance of the following Java class (getters and setters omitted):
public class ShippingHouse {
private String name;
private String description;
private List<ShippingRule> shippingRules = new ArrayList<ShippingRule>();
}
public class ShippingRule {
private ShippingHouse shippingHouse;
private String name
}
Notice that there is a 1:N relationship between ShippingHouse and ShippingRule, but each ShippingRule also has a reference to the ShippingHouse thaat owns it.
If these were Grails command/domain classes, I would bind them with request parameters
name=foo&description=bar&shippingRules[0].name=sr0&shippingRules[1].name=sr1
But it doesn't seem like this will set the reference to the owning ShippingHouse within each ShippingRule. Is there a way I can bind this automatically, or must I write the code myself?
Don,
You will need to write code to do it yourself using BindUsing or some other approach. The binder doesn't (and shouldn't) assume anything about back references from a parent to a child. If these were GORM entities and the relationship was explicit, that is different, but in your case the binder should not assume that shippingHouse property in the ShippingRule class has anything to do with the shippingRules property in the ShippingHouse class.
Also note that lucke84 said that your "private" is implicit. Make sure you understand what that means if you are going to remove them. If you remove them the compiler is going to generate public getter and setter methods for those properties, which may or may not be what you want.
If you want to implement a 1:N relationship between the two classes, you should use the right grails approach. Something like this:
class ShippingHouse {
String name
String description
static hasMany = [shippingRules: ShippingRule]
}
class ShippingRule {
String name
static belongsTo = [shippingHouse: ShippingHouse]
}
Please note that semicolons are useless and the "private" declaration on class fields is implicit.

Binding method names declaratively?

Finding the need to be able to get method names in a declarative manner (for AOP, reflection, etc) such that compiler checking enforces breaking changes etc. Good example:
invocation.Method.Name.Equals("GetAll"
.. is there a way to do this like with a lambda/generic method so i don't have to put the method name as a string literal?
I've used things like this before to get property names:
public static string GetPropertyName<T, P>(Expression<Func<T, P>> propSelector)
where T : class
{
return (propSelector.Body as MemberExpression).Member.Name;
}
.. but is there a reliable and easy way to do the same for methods?
You can do something like this with delegates:
public static string MethodName(Delegate d) {
return d.Method.Name;
}
// and to use...
MethodName(new Func<object, int>(Convert.ToInt32));
If there's a particular delegate signature you use, you can create specific overloads:
public static string MethodName(Func<object, int> d) {
return MethodName((Delegate)d);
}
MethodName(Convert.ToInt32);
You might also be able to do something with generics, if you have a play around with it.

Resources