how to not allow empty key in Guava Multimap? - guava

I have this kind of situation, where i have a multimap which i add in the end to Oracle DB, which converts empty string("") to null, is there a way i can guarantee in the code that multimap will not allow adding an empty key? (for example Multimap.put("", "some value"))
Thanks.

Both the keys and values of Guava's MultiMap are #Nullable and it doesn't have out of the box functionality to add a validation. So I would just build a validation in the code that puts the values. Something like:
if (!key.isEmpty){
multiMap.put(key, value);
} else {
log("Could not add " +value) // or throw an exception or do something else
}
Updated: after OP clarified that above doesn't apply to his use case, because parsing is done through Spring.
You could look into using ForwardingMultiMap:
A multimap which forwards all its method calls to another multimap. Subclasses should override one or more methods to modify the behavior of the backing multimap as desired per the decorator pattern.
default method warning: This class does not forward calls to default methods. Instead, it inherits their default implementations. When those implementations invoke methods, they invoke methods on the ForwardingMultimap.
https://guava.dev/releases/23.0/api/docs/com/google/common/collect/ForwardingMultimap.html
I have never used this class myself, but it sounds like you can use it to forward to a subclass of your own design. Then in that subclass you could build the validation into the put method.

Related

Where to find LinkedHashSet in jsinterop?

I have the following entity in GWT
#JsType(namespace = "my.entities")
public class MyEntity {
private Set<String> texts;
public Set<String> getTexts(){
if(this.texts==null)
this.texts=new LinkedHashSet<String>();
return this.texts;
}
public void setTexts(Set<String> texts){
this.texts=texts;
}
}
When I call myEntityVar.getTexts() in Javascript the returned object is a HashSet. It seems like jsinterop converts the java implementation of HashSet to JavaScript. But how can I create a new HashSet in JavaScript in order to use myEntityVar.setTexts(texts)? I tried an array for the "texts" param, but that doesn't work. So I somehow need to use HashSet in JavaScript.
However, I can't figure out, where to find it.
Any idea?
The short answer is that you can't - but then again, you also can't create a plain HashSet in JS either!
The reason that this works at all is that you've enabled -generateJsInteropExports, and while there is a JsInterop annotation on your MyEntity type, there is also one on java.util.Set (and a few other base JRE types). This allows for your code to return emulated java Sets without issue - any method which is compatible with running in JS is supported.
There are a few downsides:
Compiled size increases somewhat, since even if you don't use a method, it must be compiled in to your app this way, just in case JS uses it
Some methods are not supported - JS doesn't really have method overloading, so toArray() and toArray(T[]) look like the same method in JS. GWT solves this by not supporting the second method at all. (java.util.List has the same issue with remove(T) and remove(int), but it resolves it by renaming remove(int) to removeAtIndex(int) when compiled.)
If you never return these types, you'll probably want to disable this feature entirely - the -excludeJsInteropExports and -includeJsInteropExports flags to the compiler let you control what is exported.
To answer your question more directly, you have a few options that I can see:
Allow the setTexts method to be passed something else from JS, such as a JsArrayLike so that you could let users pass in a plain JS array of strings, or even a JS Set. You could go further and accept Object, and then type-check it to see what was passed in. You could even leave the Set override so it could be called from your own Java if necessary, but mark it as #JsIgnore so that GWT doesn't break when you attempt to export overloaded methods.
Create a factory method somewhere to create the Set implementation you would like your JS users to use. Since add and remove are supported, the calling JS code can build up the set before passing it in. Something like this:
#JsMethod(namespace = "my.Util")
public static <T> LinkedHashSet<T> createSet() {
return new LinkedHashSet<>();
}
Now they can call my.Util.createSet(), append items, and then pass it to your setTexts method.

validating that a field is unique using Bean Validation (or JSF)

I have an simple object that has a name
public class Foo {
private String name
}
Each user on the site may have up to 10 Foo's associated with them. Within this context, when a new Foo is created, I would like to validate that there isn't another foo associated with the same user that already exists.
I could Create a custom Bean Validator But annotations require the paramaeters to be defined during compilation. How would I then pass across the names of the existing Foos?
As suggested in various places, I could use EL expressions as an alternative way to pick up the data. This feels like using a sledgehammer to crack a nut. It also brings in a whole bunch of potential issues to consider least of all being ease of testing.
I could do class-wide validation using a boolean field
#AssertTrue(message="Name already exists")
public boolean isNameUnique() {
return (existingNames.contains(name));
}
But the validation message would not show up next to the name field. It is a cosmetic issue and this can be a backup plan. However, its not ideal.
Which brings me to the question:
Is there a simple way to write a Bean Validator that can check the value against a collection of values at the field level and meet the following restrictions ?
Previous values determined at runtime
Not using things like EL expressions
Field level validation instead of class level.
EDIT in reponse to Hardy:
The Foo class is an entity persisted within a database. They are picked up and used through a DAO interface.
I could loop through the entities but that means plugging the DAO into the validator and not to mention that the I would need to write the same thing again if I have another class that too has this constraint.
It would help to see how you want to use the Foo class. Can you extend your example code? Are they kept in a list of Foo instances. A custom constraint seems to be a good fit. Why do you need to pass any parameters to the constraints. I would just iterate over the foos and check whether the names are unique.

Pre-persistence validation for Scala case class using Salat/Casbah

Assuming that I have a Scala case class that is persisted using the Salat/Casbah/Mongo stack, I want to set up pre-persistence validation logic like I could easily do in Rails using ActiveRecord hooks or in Java using JSR 303 bean validation.
Perhaps there is a better way to think about this in a functional paradigm, but I want to accomplish something like the following:
case class SomeItem(
id: ObjectId = new ObjectId,
someProperty: String) {
#PrePersistence
def validate() = {
//perform some logic
//fail document save in certain conditions
}
}
I am having trouble finding any documentation on how to do something like this in Salat. I do see a #Persist annotation but it seems focused on serializing specific values and not creating hooks.
It seems like one option is to override the save method in the SalatDAO for my case class. Does anyone have an example of this or know of a better, built-in way to handle validation tied to a pre-persistence event?
Thanks!
Salat developer here.
Yes, #Persist is simply for ensuring that fields that aren't in the constructor are serialized - this is particularly useful for manipulating data in MongoDB. One example is where you want to ensure that all the fields are populated with a value so you can sort sensibly, but the value is an Option which may not be present.
Unfortunately, the Java driver doesn't offer lifecycle callbacks like the Ruby driver :(
But what you want should be easy enough to do. Please file an issue at https://github.com/novus/salat/issues and describe how you would like the validation to behave - we can start a discussion and I can try to get something in for you in the 1.9.2 release.

Assigning to a stub class method in Moles while using partial stubs

I've seen this question regarding partial stubs, but it does not quite tell me what I need to know.
I understand that, if I am using a Moles stub for a class (let's say, for DataService, I'm using SDataService), I can set the CallBase property to true so that, if there is no delegate for a particular method, the base implementation's method will be called. Great, but how do I assign a delegate to a particular method in this case?
If there is no way to do that, say I have an interface IDataService that I stub using SIDataService. I can easily assign a delegate to a method here. But, how do I tell it to call the corresponding method on DataService (an implementation of IDataService) if there is no delegate for a given method?
Thank you!
Edit:
I see now that the method needs to be virtual to be overridden in the first scenario above. I don't think that makes a whole lot of sense, but it is what it is.
So, focusing on the second scenario, would I have to create a Behavior? (And why isn't there one already for stubs like there is for moles?) Or is there a simpler way?
Delegates (detours) are set to stubs types the same way as mole types. For example, SIDataService.GetMemberProfile() is configured to return a mock object like this:
var memberMock = new Member() { Firstname="Joe", LastName="Schmoe" };
var stub = new SIDataService();
stub.GetMemberProfileMember = i => memberMock;

GWT: Replace AbstractPlaceHistoryMapper with a custom mapper using deferred binding

Looks like the class that is generated for PlaceHistoryMapper is hard-coded to use AbstractPlaceHistoryMapper as the super class.
So, I am trying to work around this by trying to replace this AbstractPlaceHistoryMapper with a custom mapper of mine using deferred binding . I am using the following rule in my *.gwt.xml:
<replace-with class="com.google.gwt.place.impl.AbstractPlaceHistoryMapper">
<when-type-is class="com.test.sampleapp.CustomPlaceHistoryMapper" />
</replace-with>
But for some reason the replace does not seem to be happening. CustomPlaceHistoryMapper is not getting kicked in and the generated class still uses AbstractPlaceHistoryMapper.
Any thoughts/pointers as to what might be resulting this behavior are much appreciated.
Note: I have also posted this on the GWT group but haven't received an answer so far.
To make the deferred binding work a class must be created with GWT.create(). However, AbstractPlaceHistoryMapper is only used as an extended class. So it will never be created via GWT.create, but always by instantiation the subclass. And therefor deferred binding won't work in this case. If you want a complete different implementation you have to implement a custom PlaceHistoryMapper, and manage the known tokens yourself. This also means you can't use the History annotations either.
As a side note the classnames in your rule should be swapped. But for the end result this doesn't matter, since it won't work in the first place.
It is absolutely possible to have custom history tokens (eg. #mail or #mail/bla instead of only #mail:inbox) using the out-of-the-box Place-related classes that GWT (2.0) provides.
Instead of replacing AbstractPlaceHistoryMapper you could instantiate the default PlaceHistoryMapper passing in it's constructor your implementation of PlaceHistoryMapper<T> or PlaceHistoryMapperWithFactory<T>.
eg.:
final PlaceHistoryHandler placeHistoryHandler = new PlaceHistoryHandler(new CustomHistoryMapper());
You will be able then to map tokens as you wish.
I personally recommend you to use an unique PlaceTokenizer in you mapper custom implementation so that I dont have to have an inner PlaceTokenizer class in each of your Places.
Hope that helps. Feel free to ask any doubts.