Scala annotation inheritance from trait - scala

I'm using Swagger for generating documentation. This library during parsing classes uses #JsonIgnoreProperties annotation.
I have a lot of entities extended by Entity trait
case class Device extends Entity
I don't want this entity properties to be added to output JSON. In this case I need to add such annotation:
#JsonIgnoreProperties(value = Array("net$fwbrasil$activate$entity$BaseEntity$$_baseVar", "_varsMap",
"net$fwbrasil$activate$entity$BaseEntity$$_vars", "version", "net$fwbrasil$activate$entity$BaseEntity$$persistedflag",
"net$fwbrasil$activate$entity$BaseEntity$$initialized", "net$fwbrasil$activate$entity$BaseEntity$$initializing",
"lastVersionValidation", "net$fwbrasil$activate$entity$EntityListeners$$listeners", "net$fwbrasil$activate$entity$EntityValidation$$_invariants",
"net$fwbrasil$activate$entity$EntityValidation$$_listener"))
I don't want to copy it in every entity, how can I create some abstraction for this annotation to use it in every entity class.
I checked in sources of Swagger, and it is using getAnnotation method, so is it possible to group this annotation for example using traits, or in some other way?

Related

What does "class Meta:" do in Django and Django REST Framework?

I am trying to figure out what class Meta: really do in Django.
I come across with the code below in DRF, but not sure why under class Meta: there is model = User and fields = [...]. Does it help to create a database?
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(
serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
And also what is the different with the class Meta: used in Django as below.
from django.db import models
class Ox(models.Model):
horn_length = models.IntegerField()
class Meta:
ordering = ["horn_length"]
verbose_name_plural = "oxen"
I have tried to get further understanding from both Django and DRF documentation however I did not see the explanation for model = ... and fields = [...] used in DRF class Meta.
Hope someone could help to explain the functioning principle behind. Thanks!
The Meta class is merely a convenient place to group metadata (meaning data about the data) that DRF needs to adjust its configuration, but keep this separate from the attributes of the class itself. This separation allows the Django Rest Framework (and the wider Django Framework ecosystem) to avoid clashes between configuration and the actual class definitions.
The use of an inner Meta class is a common pattern throughout Django, because this allows you to both keep this configuration separate from the fields of the class and keep it connected to the class in a way that's easy to read and easy for the framework to find. A DRF selialiser class should normally have one or more fields to help turn data into a serialized form, but the HyperlinkedModelSerializer base class can generate these fields for you if you tell it what model you wanted to serialise. The fields on the Meta class tell it you want to serialize specific fields from your User model.
By putting this configuration on the inner Meta class, they are kept in a separate namespace from the main class, but at the same time remain connected to the class they are meant to configure. Imagine a model that has a field named model and fields for example. If the HyperlinkedModelSerializer required that configuration is found in the subclass itself, you could never produce a serializer that could process something with model and fields fields!
If you wanted to know what the different options are you can use on the inner Meta class, you need to read the ModelSerialiser and HyperlinkedModelSerializer documentation in the API guide section.
For Django Models, you can refer to the Model Meta chapter of the Django documentation. As I stated above, it's the same concept but here the Meta class configures the database fields that the model supports and how the model relates to other database models you may have defined.
Last but not least, there is another answer here that confuses the term Meta with Python Metaclasses, which is a very different concept. While DRF and Django model classes lean heavily on metaclasses for their internal implementation, the class Meta: definition you use to configure the framework functionality, they are not metaclasses. They are plain classes that are only used because they make for a convenient namespace.
class Meta is used in DRF serializers to configure your serializer.
model defines the model to which your serializer is linked.
fields is a list of properties that you would like to serve in your API.
Use fields = ['__all__'] to serve all properties
Use exclude = ['your_excluded_prop_1', 'your_excluded_prop_2'] to exclude properties
The concept of Meta class comes from metaprogramming. The term metaprogramming refers to manipulating itself. Python supports a form of metaprogramming for classes called metaclasses. Meta class is mainly the inner class of your main class. Meta class is basically used to change the behavior of your main class attributes. It’s completely optional to add a Meta class to your Class. But in your Django project, you have already seen this metaclass concept available in different places like models.py, serializers.py, admin.py, etc.
Actually, this Meta class changes the common behavior of its main class like the model metaclass changing behavior using verbose_name, db_table, proxy, permissions, ordering etc, and a lot of other options. Meta class in serializer also does the exact same things it tells it the model to use and what fields to serialize by using fields, exclude, and model.
Good Luck :)

In Dagger, does an Inject annotated class also act as a Provider?

I am new to Dagger (version 2.16 on Android) and based on my reading so far, I understand that for a component, there should be a provider (#Provides or #Binds) encapsulated in a module (#Module). Going through a lot of samples, I see code which has some objects which are not offered in any Module, nor are they being instantiated using new.
It is also my understanding that in order to access the dependencies in a module, a consumer class needs to inject itself in the component graph (components usually offer a method to inject classes). The code examples are not doing this either.
Here's some code demonstrating both my concerns. RecipePresenter is not being provided in any module, but still RecipeActivity is using it.
A possible explanation I could think of is that #Inject, in addition to requesting the dependency also adds/injects the requesting class (RecipePresenter in the linked code) into the component graph. But assuming there are multiple components/subcomponents, which component does the class using #Inject constructor gets attached to? If my understanding is correct, why do activities and fragments have to inject themselves manually in the component - shouldn't they be auto-injected if they declare a variable annotated with #Inject?
RecipePresenter has an #Inject-annotated constructor, which allows it to be provided. The #Inject annotation on the recipePresenter field within RecipeActivity does not help, just the #Inject-annotated constructor.
class RecipePresenter #Inject constructor(
private val useCase: RecipeUseCase,
private val res: StringRetriever) :
RecipeUseCase.Callback {
From the Dagger User's Guide:
Use #Inject to annotate the constructor that Dagger should use to create instances of a class. When a new instance is requested, Dagger will obtain the required parameters values and invoke this constructor.
If the class with the #Inject-annotated constructor also has a defined scope, then the binding will only affect components with the same scope annotation: An #ActivityScope class wouldn't be accessible from a #Singleton component, for instance. If the class has no scope defined, then the binding could appear on any and all components where it is needed, which is fine: The implementation is always the same, defined by the constructor itself.
#Inject has different meanings based on what it's annotating:
When you annotate a field with #Inject, it indicates that the DI system should set that field based on values from the DI system when it injects that object.
When you annotate a method with #Inject, it indicates that the DI system should call that method with parameters based on values from the DI system when it injects that object.
When you annotate a constructor with #Inject, it indicates that the DI system is allowed to call that constructor in order to create that object (which triggers the field and method injection above). In that sense it does act like a built-in Provider.
In Dagger specifically, #Provides methods take precedence over #Inject constructors (if they both exist for the same class), and unlike in the JSR-330 spec Dagger requires an #Inject-annotated constructor even when no other constructors are present. From the Dagger User's Guide:
If your class has #Inject-annotated fields but no #Inject-annotated constructor, Dagger will inject those fields if requested, but will not create new instances. Add a no-argument constructor with the #Inject annotation to indicate that Dagger may create instances as well.
Classes that lack #Inject annotations cannot be constructed by Dagger.
Finally, to answer your question about why activities and fragments need to inject themselves: Android is allowed to reflectively create Activity/Fragment/View objects without Dagger's help or participation. This means that nothing triggers the field and method injection described above, until you call a members-injection method on the component that instructs Dagger to populate those fields and call those methods. Consequently, you should never see an #Inject-annotated constructor on Application, Activity, Service, Fragment, View, ContentProvider, and BroadcastReceiver subclasses in Android: Android will ignore the #Inject annotation, so you might as well take control over injection yourself, manually or through dagger.android.

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.

Entity Framework 4.0 Autogenerated Classes not marked as Serializable

One strange thing i've got to see in Entity Framework 4.0 V2 Auto Generated Classes(tt) is that the classes are not marked as Serializable. Although they are having DataContract attribute for WCF.
Now the problem is, when I store the POCO object into viewstate it throws me an exception saying that the class is not serializable.
If I generate the classes without the t4 templates or using the defualt class generating scheme, what i see is that the generated classes are having the Serializable attribute on them.
But unfortunately i can not make use of the default Entity Generation Scheme. Since I want to accomodate some custom logic to the autogenerated class which is possible through t4 templates only.
Now what i want to know is:
1) Why the Serializable Attribute is not there in the autogenerated class or am I making any mistake or i am towards a wrong approach.
2) Is it a good idea to customize the EF 4.0 T4 template to accomodate Serializable attribute.
Looking for your valuable suggestion.
Thanks,
Burhan Ghee
Yes you can modify the template. Look at Adding [DataMember] [DataContract] attributes in Entity Framework POCO Template for exactly what you need to do to fix your template. Look specifically at the WriteHeader function in the template.
The purpose of T4 template is allow you to customize. Customize it fearlessly! You are not only encouraged to customize template, but also the edmx file that your template is based on.
see this http://blogs.msdn.com/adonet/archive/2010/03/05/updated-data-model-designer-extension-starter-kit.aspx

RIAServices unsupported types on hand-built DomainService

My EF model was generated from my SQL Server database. I then generated a DomainService for RIAServices against the EF model. One of the entities is called "EntryCategories". The DomainService created this method:
public IQueryable<EntryCategories> GetEntryCategoriesSet()
{
return this.Context.EntryCategoriesSet;
}
Since my user interface display model looks quite different from the physical model, I decided to write my own DomainService for that and related entities. Yes, I know we are meant to modify the generated one but it has so much stuff in there and I wanted to focus on a small thing.
I removed the EnableClientAccess attribute from the generated DomainService and added a new class called ClientDomainService, and encapsulated in it the generated DomainService:
[EnableClientAccess()]
public class ClientDomainService : DomainService
{
// the generated domain service encapsulated in my new one.
private DataDomainService _dcds = new DataDomainService();
// reimplement one of the DataDomainService methods
public IQueryable<EntryCategories> GetEntryCategories()
{
return (from t in _dcds.GetEntryCategoriesSet() where t.EntryCategoriesVersions.EntryCategoriesVersionId == datahead.EntryCategoriesVersions.EntryCategoriesVersionId orderby t.DisplayOrder select t);
}
}
The very fist thing I tried is to reimplement the GetCateogoriesSet method but with the underlying data filtered based on another entity in my class (not shown). But when I build this, an error shows up:
Entity 'DataProject.Web.EntryCategories' has a property 'EntryCategoriesVersionsReference' with an unsupported type
If I comment out my CientDomainService, replace the EnableClientAccess attribute on the generated DomainService, and place the analagous linq filtering in the original GetEntryCategoriesSet method, the project compiles with no errors.
What is so special about the generated DomainService that my new one doesn't have? Is it that metadata.cs file?
What's special about the generated domain service is not the .metadata.cs file (you can keep it, and use it, but it doesn't solve your problem).
The problem appears somehow because RIA services (?) needs a 'domain service description provider' for the exposed Linq to EF entities. The LinqToEntitiesDomainService class has the LinqToEntitiesDomainServiceDescriptionProviderAttribute, already applied, so the generated domain services which inherit from it also inherit the provider.
When you build your own custom domain service, derived from DomainService, and expose entities through it, you need to apply this attribute yourself. Furthermore, since the provider cannot infer the object context type from the domain service base class (which it can and does if the base class is LinqToEntitiesDomainService), you need to specify the object context type in the attribute constructor, like this:
[EnableClientAccess()]
[LinqToEntitiesDomainServiceDescriptionProvider(
typeof(YourObjectContextType))]
public class ClientDomainService : DomainService
{
...
}
That should fix it.
Note that this means if you had hoped to abstract your object context away from your domain service, you'll be disappointed. I had opted for the seemingly popular repository model where all code that operates on the object context goes into a provider used by the domain service. This facilitates unit testing, but evidently doesn't remove the domain service's dependency on the object context. The context is required for RIA Services to make sense of your entites, or at least those referenced by the domain entity (such as EntryCategoriesVersions in your case).
If you want to expose a specific entity on a domain service you will have to provde at least one query method for it. This is also required when the entity is only accessed as a child of another entity.
In this case you need to add the EntryCategoriesVersions entityset to the domain service, to get the scenario working correctly.
What type is EntryCategoriesVersionsReference ? Try adding a [DataContract] annotation against the type, and appropriate [Key] and [DataMember]. It should help with marshalling.
For me, the fix for this error was to add a default constructor to the return type.
In OP's example, the property 'EntryCategories.EntryCategoriesVersionsReference' needs to be of a type with a default constructor.