How to have a generic solution to parse an unknown class to Json in scalaJs - angularjs

I'm using ScalaJs angular and Upickle and I try to create a filter to transform an unknown class to JSON.
What I tried :
my scope :
var myScope: MyClass = js.native
my filter:
#injectable("copy")
class CopyFilter extends Filter[Any] {
override def filter(any: Any): js.Dynamic = {
val myClass = any.getClass
fromClassToJsValue[myClass](any)
}
}
my function
def fromClassToJsValue[A](value: A)(implicit serializer: Writer[A]): js.Dynamic =
JSON.parse(write(value))
In this case my problem is getClass which returns Class[_] and not MyClass
Is there any solution to find MyClass? (Or maybe any other solution to derive a type Any?)

Broadly speaking, uPickle isn't designed to deal with that; I don't think any of the other JSON serializers are, either. That sort of Any-friendly serialization is usually based on reflection, which mostly isn't available in the JavaScript environment.
I suspect you do need a Filter per case class, albeit probably a one-liner. (Possibly done as a base trait that you mix into the case classes themselves, but I don't know Angular, so I know don't what the constraints look like.)

Related

State Schema Evolution with POJOs

I'm using flink 1.11 with Scala and i have a question regarding the schema evolution using a POJO.
In the documentation is written, that POJOs are supported for state schema evolution (with some limitations).
Are Scala case clases also considered as POJO and therefore supported?
case class WordCount(word: String, count: Int)
Or have i to write something like this:
class WordCount(var word: String, var count: Int) {
def this() {
this(null, -1)
}
}
Case classes are not POJOs. In particular, they do not satisfy:
The class has a public no-argument constructor
All non-static, non-transient fields in the class (and all superclasses) are either public (and non-final) or have a public getter- and a setter- method that follows the Java beans naming conventions for getters and setters. (afaik case classes have final fields with getters in the generated JVM class)
You can implement all required things in a normal scala class but your IDE might not support you well. An option is to create your class in Java, let your IDE beanify it and convert it to scala (or use it directly).
There is also the option to create evolution support for case classes with a custom serializer. That will eventually be available by Flink. (You could also go ahead and contribute it).

Swift - Array with specific class type

How can i create array which will hold objects belonging a specific class.
class BaseObject {}
class Derived1: BaseObject {}
class Derived2: BaseObject {}
class Derived2: BaseObject {}
I need to create array in which will hold only Object derived from BaseObject
Something like - var array : [BaseObject.Type] = []
Is there a way to specify this ?
Also, I should be able to use it something like this
if let derived1 = object as? [Derived1] {
}
else if let derived2 = object as? [Derived2] {
}
You can obviously define your array as an array of BaseObject:
var objects: [BaseObject] = [] // or `var objects = [BaseObject]()`
But it's going to let you create a heterogenous collection (of either BaseObject or Derived1 or Derived2 or of any other subclass). That's a core OO design concept (the Liskov substitution principle) that any subclass of BaseObject should (and will) be permitted.
If all you want is to say that you can only have an array of one of the subtypes, you can obviously just define your array as such, e.g.:
var objects: [Derived1] = []
That will obviously allow only Derived1 objects (and any subclasses of Derived1.
90% of the time, the above is sufficient. But in some cases, you might needs some collection with methods that require some inherited base behavior, but for which you don't want to allow heterogenous collections. In this case, I might consider a more protocol-oriented pattern:
Bottom line, should we be subclassing, or should we be using a protocol-oriented approach? I.e. is BaseObject actually something you'll instantiate for its own purposes, or is it there merely to define some common behavior of the subclasses. If the latter, a protocol might be a better pattern, e.g.:
protocol Fooable {
func foo()
}
// if you want, provide some default implementation for `foo` in an
// protocol extension
extension Fooable {
func foo() {
// does something unique to objects that conform to this protocol
}
}
struct Object1: Fooable {}
struct Object2: Fooable {}
struct Object3: Fooable {}
This yields the sort of behavior that you may have been using in your more OO approach, but using protocols. Specifically, you write one foo method that all of the types that conform to this protocol, e.g., Object1, Object2, etc., can use without having to implement foo themselves (unless, of course, you want to because they need special behavior for some reason).
Because this eliminates the subclassing, this then opens the door for the use of generics and protocols that dictate some generalized behavior while dictating the homogenous nature of the members. For example:
struct FooCollection<T: Fooable> {
private var array = [T]()
mutating func append(_ object: T) {
array.append(object)
}
// and let's assume you need some method for your collection that
// performs some `Fooable` task for each instance
func fooAll() {
array.forEach { $0.foo() }
}
}
This is a generic which is a homogenous collection of objects that conform to your protocol. For example, when you go to use it, you'd declare a particular type of Fooable type to use:
var foo = FooCollection<Object1>()
foo.append(Object1()) // permitted
foo.append(Object2()) // not permitted
foo.fooAll()
Now, I only went down this road because in comments elsewhere, you were inquiring about generics. I'd personally only go down this road if the (a) collection really needed to be homogenous; and (b) the collection also wanted to implement some shared logic common to the protocol. Otherwise, I'd probably just stick with a simple [Derived1] (or [Object1]). The above can be powerful when needed, but is overkill for simpler situations.
For more discussion about protocol oriented programming, the homogenous vs heterogenous behavior, traditional stumbling blocks when you're coming from a traditional OO mindset, I'd refer you to the WWDC 2015 video, Protocol-Oriented Programming in Swift, or it's 2016 companion video that builds upon the 2015 video.
Finally, if you have any additional questions, I'd suggest you edit your question providing details on a practical problem that you're trying to solve with this pattern. Discussions in the abstract are often not fruitful. But if you tell us what the actual problem you're trying to solve with the pattern in your question, it will be a far more constructive conversation.

Kotlin object vs companion-object vs package scoped methods

I have written this methods in Kotlin and analysed the bytecode:
Situation 1
class A {
object b {
fun doSomething() {}
}
}
Situation 2
class A {
companion object b {
fun doSomething() {}
}
}
Situation 3
fun doSomething() {}
Bytecode Result
Situation 1: class Test$asb, public final doSomething()I
Situation 2: class Test$Companion, public final doSomething()I
Situation 3: class TestKt, public final static doSomething()I
My questions are:
I have an enum class, and I want to return an enum instace given an enum variable, for instance, findById (enum(id, color)). How would I do it? Companion Object? object?
It seems the only way to have a real static method is in package level, without class declaration. But that becomes a little bit too global. Is there any way to access it via: ClassName.staticMethod, staticMethod being really static.
Provide meaningfull examples of package declaration methods, companion object and object.
Context. I have been coding in Kotlin and I find it amazing. But sometimes I need to make a decision: for example, a heavy immutable property which in java I would declare as static final, but in Kotlin I find it hard to "find an equivalent".
If you have a function which performs some action closely related to a class but doesn't require a class instance, such as your findById example, you should put it in the companion object of the class.
If you want to expose a method as a static method to Java code, you can annotate it with the #JvmStatic annotation.
If a function does not require an instance of a class, then it is your design decision where to put it. Use package level if it is package-specific, use a class companion if it closely relets to the class (for example other classes in the package have similar functions).
Note that enum has several in-build properties and patterns:
enum class Colour(val value: Int) {
black(100), red(200), green(300)
}
fun colourById(id: Int) = Colour.values[id]
fun colourByValue(value: Int) = Colour.values.first {it.value == value}
fun colourByName(name: String) = Colour.valueOf(name)
I would suggest to develop voddan answer:
enum class Color {
RED,
BLUE,
GREEN;
companion object Utils {
fun findById(color: Color): Color {
return color;
}
}
}
And to test
#Test
fun testColor() {
println(Color.Utils.findById(Color.valueOf("RED")));
}

ApiTransformer for parametrized, unavailable type

I'm using Objectify and wish to have its Key<> type passed around in my API. I've created an ApiTransformer, but my questions is where to declare it, since the serialized Key<> class is not available, hence I cannot declare its transformer as a class annotation. I tried declaring it in the #Api annotation, but it doesn't work, I still get the error:
There was a problem generating the API metadata for your Cloud Endpoints classes: java.lang.IllegalArgumentException: Parameterized type com.googlecode.objectify.Key<[my package].User> not supported.
The ApiTransformer looks like:
public class KeyTransformer implements Transformer<Key<?>, String> {
public String transformTo(Key<?> in) {
return in.getString();
}
public Key<?> transformFrom(String in) {
return Key.valueOf(in);
}
}
And in my #Api I have:
#Api(name = "users", version = "v1",transformers = {KeyTransformer.class})
Unfortunately you can't. As you said you need to declare it on the Key class, your only chances to make this work are either.
1) Recompile the Key class for objectify with the #transformer annotation.
2) Extend the Key class with your own implementation and define the transformer there.
I don't really like any of those options so the way i usually resolve this is to hide the key object getter (by using #ApiResourceProperty(ignored=AnnotationBoolean.TRUE)) and only expose the id from that key.
That way you get a Endpoints frendly object, the only downside is you'll have to reconstitute the key using Key.create(YourClass.class, longId) manually whenever you need it.
You can add transforms to 3rd party classes by listing the transform in #Api annotation. I'm not dead sure it'll work parameterized class, but I don't see why not.
https://cloud.google.com/appengine/docs/java/endpoints/javadoc/com/google/api/server/spi/config/Api#transformers()

Ignore field with annotation for JSON serialization but not for Mongo in MongoJack

Is there any possibility to ignore field for JSON serialization (for web display) but not for mongo (internal serialization) ?
I`ve tried so far all these methods but field was also ignored for Mongo, or not ignored in both in case of some variations
Jackson: how to prevent field serialization
Ok, I finally solved this.
objectMapper.writerWithView(Views.Public.class).writeValueAsString(lo));
writeValueUsingView is from another version of Jackson, so it wasn't working
Custom serialization for web/mongo can be solved by using #JsonView annotations, try along these lines:
class Views {
static class OnAllViews {}
static class OnlySomeViews extends OnAllViews {}
...
}
public class Thing {
#JsonView(Views.OnAllViews.class) Integer id;
#JsonView(Views.OnlySomeViews.class) String name;
}
and then you can call the appropriate level of serialization through writeValueUsingView method.
objectMapper.writeValueUsingView(out, beanInstance, ViewsPublic.class);
You can read more about it here.

Resources