I'm having difficulty getting #JsonIgnore to work with Cloud Endpoints.
If I add #JsonIgnore to my getter from com.google.appengine.repackaged.org.codehaus.jackson.annotate.JsonIgnore the property is successfully suppressed. (But then I get the nasty 'Warning Error' that my app might break)
However, when I switch #JsonIgnore to org.codehaus.jackson.annotate from jackson-core-asl-1.9.11.jar, Generate Cloud Endpoint Client Library ignores my #JsonIgnore annotation and creates the model class with the property I am trying to suppress.
Any ideas?
Don't use #JsonIgnore, use #ApiResourceProperty instead:
#ApiResourceProperty provides provides more control over how resource
properties are exposed in the API. You can use it on a property getter
or setter to omit the property from an API resource. You can also use
it on the field itself, if the field is private, to expose it in the
API. You can also use this annotation to change the name of a property
in an API resource.
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public String getBin() {
return bin;
}
Related
I read data from Firebase database into a Kotlin/Android program. The key names in Firebase are different from those of the corresponding Kotlin variables. I test this code with flat JSON files (for good reasons) where I retain the same key names used in Firebase, so I need to transcribe them too.
Firebase wants to annotate variables with #PropertyName; but Gson, which I use to read flat files, wants #SerializedName (which Firebase doesn't understand, unfortunately.)
Through trial and error I found that this happens to work:
#SerializedName("seq")
var id: Int? = null
#PropertyName("seq")
get
#PropertyName("seq")
set
Both Firebase and Gson do their thing and my class gets its data. Am I hanging by a thin thread here? Is there a better way to do this?
Thank you!,
You can probably solve this by using Kotlin's #JvmField to suppress generation of getters and setters. This should allow you to place the #PropertyName annotation directly on the property. You can then implement a Gson FieldNamingStrategy which checks if a #PropertyName annotation is present on the field and in that case uses its value; otherwise it could return the field name. The FieldNamingStrategy has to be set on a GsonBuilder which you then use to create the Gson instance.
I'm getting a circular reference error when serializing a component. Usually this can be fixed using
$normalizer->setCircularReferenceHandler()
However, I'm using the SerializerInterface like this:
/**
* #Route("/get/{id}", name="get_order_by_id", methods="GET")
*/
public function getOrderById(SerializerInterface $serializer, OrderRepository $orderRepository, $id): Response
{
return new Response($serializer->serialize(
$orderRepository->find($id),
'json',
array('groups' => array('default')))
);
}
Is it possible to fix a circular reference error when serializing using this interface?
You totally can. Just add this in your framework config.
framework:
serializer:
circular_reference_handler: App\Serializer\MyCustomCircularReferenceHandler
This handler will work globally. Make sure you register it as a service. I does not need to implement any interface. So just a class with an __invoke() will suffice. That invoke will receive the object that is being "circle referenced" as the only argument.
You can either return the id or do some really cool stuff, like creating a uri for the resource. But the implementation details are totally up to you, as long as you don't return the same object, everything will be fine.
:)
According to the Symfony API Reference on the interface there doesn't look to be a way to execute that function or retrieve the normalizer.
Even in the Serializer, there doesn't look to be a way to retrieve the normalizer after creating the serializer.
You're best off creating the normalizer before the serializer to achieve this, rather than injecting the interface via config files. (Relevant docs link)
I'm using realm as database and kotlin as language.
I implemented my custom setter method for a property.
Does Realm call this setter somehow?
For example:
open class Human(): RealmObject()
{
open var Name: String = ""
set(value)
{
setName(value)
}
}
Now I also have a property changeDate and it would be nice if I can set the changeDate automatically in the setNameto new actual day.
But I can't do this if Realm calls this method also.
Thanks
I've tried this with Kotlin 1.1.1 and Realm 3.0.0, and it doesn't call the custom setter, it assigns the value in some other way (which means that it even works if your custom setter is empty, which is a bit unexpected).
Edit: Looked at the generated code and the debugger.
When you're using an object that's connected to Realm, it's an instance of a proxy class that's a subclass of the class that you're using in your code. When you're reading properties of this instance, the call to the getter goes down to native calls to access the stored value that's on disk, inside Realm.
Similarly, calling the setter eventually gets to native calls to set the appropriate values. This explains why the setter doesn't get called: Realm doesn't need to call the setter, because it doesn't load the values into memory eagerly, the proxy is just pointing into the real data in Realm, and whenever you read that value, it will read it from there.
As for how this relates to Kotlin code, the calls to the proxy's setter and getter that access the data inside Realm happen whenever you use the field keyword (for the most part).
var Name: String = ""
get() {
return field // this calls `String realmGet$Name()` on the proxy
}
set(value) {
field = value // this calls `void realmSet$Name(String value)` on the proxy
}
Please look at the following code:
public function __construct($error_code)
{
$translator = new Translator('en');
$translator->addLoader('yaml', new YamlFileLoader());
$translator->addResource('yaml', dirname(__DIR__).'/Resources/translations/messages.en.yml', 'en');
$this->setErrorCode($translator->trans($error_code));
}
I am new to symfony. I have created a class MyProjectExceptions which extends Exception. Now when I have to throw a custom exception I call this class where I get the $error_code. Now this $error_code is a constant of another class which has its locale in MyBundle/Resources/transalations/messages.en.yml which will be used to throw as exception message.
Now my question are following:
How can I avoid addResource, so it can automatically add it based on Locale and find the string?
How to access serviceContainer in this class so that I can access session to set and get locales OR other services.
Can we set the default Loader as well.
In above code I am creating an instance of Translator class and manually passing 'en'. but it should pick default locale or user set locale.
I tried many solutions but not able to get the desired results.
Any help would be appreciated. Thanks in advance.
You need to register your class as Symfony service. Read the documentation: http://symfony.com/doc/current/book/service_container.html#creating-configuring-services-in-the-container
After that you can inject other services (like Translation) in your constructor. It will use all parameters that you have already set.
If you inject translator service it will pick the parameters that you have already set. For example, if you defined parameters for translator (including default locale) at config.yml, then you overrode this locale with parameter in route, you will get translator service set up with this locale. And it will automatically use resources that are lied in appropriate directories.
I don't understand why JSR 303 (bean validation) is for the getter methods and not setter? Isn't it more logical to put it under setter method since that is the entry point into a field and validation should be checked prior to that?
Annotating getters doesn't mean that validation is performed when a getter is invoked. It is just used to identify the property to which a constraint shall apply.
The big advantage of putting constraints on (usually public) getters instead on (typically private) fields is that the constraints are part of the type's public API that way. They will even be added to the generated JavaDoc. A user of a type knows that way which constraints apply to it without looking into its internal implementation.
Another advantage of annotating getters is that constraints can be put at methods on base classes or interfaces and also apply for any sub-types/implementations.
Its a very good question and something that I have never paid attention to. But I think I know the answer ( and also why I never got this question myself).
If you are looking at this, from the point of view that, the annotation defines where the validation will happen, then putting it on getter does not make sense. ( why not validate while storing the value itself..). But this is not how it works...
The programmer needs to tell the validation framework, which properties needs to be validated. So you can put the annotation directly on the attribute (which I prefer) or you can put it on the getter. Both of them signify read operation. The Framework needs to read all the attributes of your class, that will have to be validated. So in this case, putting on setter makes no sense at all.. The key to understand is the perspective...
I hope it makes sense.
Consider this code:
public class BeanValidation {
private int nameSetCount = 0;
private int nameGetCount = 0;
private String name;
public String getName() {
this.nameGetCount++;
return name;
}
public void setName(String name) {
this.nameSetCount++;
this.name = name;
}
}
Put annotation over private String name;
Annotation identifies field easily just looking at the field.
Put annotation over public String getName()
Annotation identifies field easily just looking at the returned field.
Put annotation over public void setName(String name)
Annotation can not identify field looking at the modified field because there can be more than one.
Bean Validation is called that way for a reason. It is applied to an initialized bean. So, first off, you initialize it with everything you have, then you pass it(or it is passed explicitly) to the Bean Validation implementation, which will rely on the validation annotations when accessing the fields.
In case of Spring MVC validation handling starts at:
result = execVal.validateParameters(
invocation.getThis(), methodToValidate, invocation.getArguments(), groups);
inside MethodValidationInterceptor. From here on, it's passed to validation implementation, in most cases Hibernate.
invocation.getArguments() will contain all the method arguments already initialized with the given values, regardless of validation annotations.