Is it possible to generate a public default constructor as well as static factory method for an Immutables builder? - constructor

I'm trying to define a builder for an Immutables value that has both a public default constructor and a static factory method, i.e.
new CustomerBuilder().name("Joe").age(21).build()
AND
CustomerBuilder.builder().name("Joe").age(21).build()
I want the default constructor available because I'm using the builder with the DynamoDbEnhanced client, which expects a public default constructor for the builder to be available. I prefer the static factory way of initializing builders, so that is why I would like the static factory style to also be available.
Is there a combination of properties in the style I can set to accomplish this?
Here is the reference for the possible annotations that can be used in defining an Immutables Style.

Related

Cannot Deserialize LifeRay Service Model Object from JSON that came from ElasticSearch, Default Constructor not Found

Using LifeRay portal and ElasticSearch, Serializing custom object composed from ServiceModel Objects, Serialisation goes fine:
public String toJSON(){
return JSONFactoryUtil.looseSerializeDeep(this);
}
I index this into ES which is also fine, it contains list of those objects as well as single object, no problem.
When I Deserialize this I get this Error:
10:10:53,972 ERROR [ExceptionHandlerBridgeImpl:78] jodd.json.JsonException: Default ctor not found for: eu.project.drives.platform.model.model.TainingProvider
For each parameter which is Object from Service Model.
Code (should be ok as well, example for one field):
JSONObject obj = JSONFactoryUtil.createJSONObject(h.getSourceAsString());
TainingProvider t = JSONFactoryUtil.looseDeserialize(obj.getString("provider"), TainingProvider.class);
I cannot simply induce the Default constructor since it is generated by service builder nor I can do the "TainingProviderImpl.class" since it is different project but the Impl class should be what is called through the "TainingProvider.class" and it includes the default constructor.
Thank you.
The provided type when doing a deserialize is an interface in your example, so the internal Parser (here Jodd) might not find an implementation class to use as a bean class.
I did not find a nice solution, but used the internal Jodd parser directly.
When you subclass jodd.json.JsonParser you can overwrite the protected method for instantiation.
#Override
protected Object newObjectInstance(Class targetType) {
if (targetType.isAssignableFrom(TainingProvider.class)) {
return TainingProviderLocalServiceUtil.createTainingProvider(0L);
}
return super.newObjectInstance(targetType);
}
Now you can use the parser directly via parser.parse(obj.getString("provider"), TainingProvider.class)
I am not sure if it possible to hook in this instantiation hints to Liferays JSONFactoryUtil, which would be nicer instead of having a direct dependency to the jodd Parser in your module.

Jackson - ignore Map superclass when serializing

I have a few model classes that extend LinkedHashMap<String, Object>: they define getters and setters which wrap the Map's get and put methods. I am trying to serialize instances of these classes using Jackson (with RESTEasy), but Jackson refuses to pay attention to my getters, which are annotated with #JsonProperty. Instead, it is only serializing the key-value pairs of the backing map. I tried using #JsonAutoDetect to disable auto-detection for all methods and fields, but that didn't change anything. Is there a way to prevent Jackson from automatically serializing a Map, or must I create new model classes that don't extend LinkedHashMap<String, Object>?
I agree with #skaffman's response. But if you could not easily change inheritance structure drastically, there may be ways around this.
One possibility is that if you do have an interface that defines getters/setters, you could add
#JsonSerialize(as=MyInterface.class)
#JsonDeserialize(as=MyInterface.class)
which would force Jackson to only use whatever is available via specific interface.
Custom serializers/deserializers are also a possibility, but that's quite a bit of work.
I have a few model classes that extend LinkedHashMap<String, Object>: they define getters and setters which wrap the Map's get and put methods
This is a classic example of when not to use inheritance: you're finding that some other piece of code (i.e. Jackson) is treating your class like an instance of its superclass, which isn't what you want it to do. In cases like these (and also in general), it's usually better to use composition rather than inheritance.
I recommend rewriting your model class to contain a map, rather than extending one. You get much more control than way, and the resulting model is less brittle. If you need to view your model as a Map, then implement an asMap method (or something similar) which renders that view.
You can implement your own org.codehaus.jackson.map.DeserializerProvider which extends Jackson's org.codehaus.jackson.map.deser.StdDeserializerProvider and overwrite method _createDeserializer:
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.deser.StdDeserializerProvider;
import org.codehaus.jackson.map.DeserializationConfig;
...
class MyDeserializerProvider extends StdDeserializerProvider {
#Override
protected JsonDeserializer<Object> _createDeserializer(DeserializationConfig config, JavaType type, BeanProperty property) throws JsonMappingException {
if (type.isMapLikeType()) { // (1)
return this._factory.createBeanDeserializer(config, this, type, property);
} else {
return super._createDeserializer(config, type, property);
}
}
}
(1) use if-condition that meets your needs
The custom deserializer is registered directly at the ObjectMapper:
ObjectMapper om = new ObjectMapper();
om.setDeserializerProvider(new MyDeserializerProvider());
I tested this with Jackson 1.9.11.
In newer versions of jackson (>= 2.9, I guess) simply annotate your class with
#JsonFormat(shape = JsonFormat.Shape.OBJECT)

mocking the static methods and private members using asmock

1.Is there any way to access the private data members of a class in action script using asmock framework? I tried using syntax like
ContentPlayer[“getContentPlayer”]=mockContentPlayer;
Where in getContentPlayer is a private member and mockContentPlayer is alias am creating, but its not working well, I doubt whether I can do like this?
Is there any way to mock the public static methods of actionscript using asmock?
asMock uses inheritance to intercept calls to the methods. As it's not possible to override a static or private method in the AVM, it's not possible for asMock to add support for it.
I'd recommend abstracting the static call with an interface and accepting an instance in the constructor.
You can't access private fields from outside of class in AS3. Period.

When should I use/examples of nested classes?

Please retag this question to include languages to which it is relevant
So my java book had a whole chapter on nested classes, but ended on the note that you should only really use them when it comes to "modeling composition relationships and implementing internals of a class you want to hide". So lets discuss when you would want to use nested classes and some examples.
A nested/inner class is just a class that's only ever used specifically in the context of another class, which doesn't have it's own class file. If it's linked to an instance, it can only be instantiated in the context of a parent class instance; it can see private data, or only private static data if it's a static class.
The java developer site has a nested classes tutorial with one example:
http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
A couple examples of usage:
Hide a concrete implementation of an
interface:
(Thinking of a database session for a tool like Hibernate): Suppose you have a Session interface, and a SessionFactory which returns an instance of a Session. The SessionImpl concrete class that implements the Session interface could be an innner class of the factory that knows how to construct and initialize it.
Supply information by implementing an
interface:
In the Wicket web framework, each GUI component has an associated "model", whose job is to wire data to the component. The interface looks something like:
public interface IModel extends IDetachable {
public Object getObject();
public Object setObject();
}
Suppose you have some special logic to retrieve data for a custom GUI component that you've written. Since no other component retrieves data the same way, you could use an anonymous class at the point where the IModel is supplied to take care of the data retrieval. If you have another point in the same class where you need to reuse your IModel implementation, you could make it an inner class. Later, if you need the model elsewhere, you could convert it to a top-level class.
Generally you use an inner class in a situation where you need a class definition, but that class is only usable or only makes sense in the context of the parent class.
A real life usage i had with nested classes, was in a global settings object.
The parent class was a Singleton, with nested classes as settings categories.
Settings
File settings
Print settings
Etc.
There was no real point in making the inner object as separate classes, as their would be no use for them outside the settings class scope.
I use nested classes for encapsulating algorithms that would be usually done as a method with lots of arguments. I use class that has raw data and I put algorithms into separate file in nested class (using partial keyword). That way I can put properties for that algorithm and its (working) data lives after algorithm is done.
I know that can be easily done without nested classes but this feels right because algorithm is purposely built for parent class.
public partial class Network
{
partial void initFDLF()
{
fdlf=new FDLF(this);
}
public FDLF fdlf;
public class FDLF
{
internal bool changed=true;
internal bool pvchange=true;
public double epsilon = 0.001;
public bool fdlfOk=false;
public void init(){...}
public void run(){...}
...

How do you create your Factories?

So, coming upon the subject of Factories, I'm wondering how they are set up.
From where I stand, I can see 3 types of Factories:
All In One
A factory that basically contains all of the classes used in an application. It feels like it is just having a factory for the sake of having a factory, and doesn't really feel structured.
Example (Where ClassA, Class B, and ClassC have nothing in common except being in the same App):
class Factory
{
public static function buildClassA()
public static function buildClassB()
public static function buildClassC()
}
Code samples provided are in PHP. However, this question is language-agnostic.
Built-In Factory
The next one is mixing in static functions with the regular functions in order to make special creation patterns (see this question)
Example:
class ClassA
{
public static function buildClass()
public function __construct()
}
Factory On-the-Side
The last one I can think of is having a factory for individual classes, or individual sets of classes. This just seems to variable to be used in an uniform manner.
Example (Where ClassA, B, and C are related, and 1, 2, and 3 are related):
class FactoryAlpha
{
public static function buildClassA()
public static function buildClassB()
public static function buildClassC()
}
class FactoryNumeric
{
public static function buildClass1()
public static function buildClass2()
public static function buildClass3()
}
My question is: Are all of these bad ideas, are any of them bad ideas? Are there other ways of creating factories? Are any of these actually good ideas? What is a good/best way to create Factories.
The point of a factory seems to be to have the code that uses it not need to know which concrete class will be constructed (this should be handled by configuring the factory). That seems to rule out "All-in One" and "Factory-on-the-Side".
I like the approach that Java libraries often use: You have a static method that creates the Factory. The Factory has a getInstance method that creates the instance. This gives you two points of configuration (via system properties): The default FactoryImpl has a number of settings, such as the class it should produce, and if these configuration options are not enough, you can also swap out the FactoryImpl altogether.
As for "All-in One" vs "Factory-on-the-Side", a Factory should not produce unrelated classes I think. Again, it Java terms, every factory produces instances of a certain interface.
"All-in-One" sounds like something that should be replaced with Dependency Injection (where you have a container that produces all kinds of instances and injects them into the application).
If you are really interested in "Preferred technologies", I'd replace them all with Dependency Injection.
If that seems to heavy, just remember that you may not be seeing every use for your factory so don't "New" a hard-coded class in your factory. Instead, have a "Setter" that can specify what class needs to be injected.
This will come in handy later when you are unit testing and need to start injecting mock classes.
But as you make this more general, abstract and reusable, you'll end up back at DI. (Just don't say I didn't warn you)
There's really just two standard sorts of factories, at least according to GOF and the slew of patterns books that followed: The basic Factory, and the Abstract Factory.
A Factory generally returns a concrete instance that the caller refers to through an interface, like so:
// createWidget() here instantiates a BigWidget or SmallWidget or whatever the context calls for
IWidget widget = WidgetFactory.createWidget(someContextValue);
Using a factory with an interface in this way keeps the caller from being coupled into a specific type of the returned object. Following the venerable Single Responsibility Principle, a factory should do one thing, that is, return a concrete instance of the interface that was called for, and nothing more. A basic factory should only have the job of creating one type of object.
An Abstract Factory, on the other hand, can be thought of as a factory of factories, and might be closer to what you were thinking of as an "all in one" factory. An Abstract Factory is usually configured at start-up to return a group of related factories, for instance factories that might create a particular family of GUIs depending on a given context. This is an example of Dependency Inversion that has largely been replaced by using IOC containers like Spring.