API , How to make it accept case insensitive ENUM - deserialization

I have added a json media dependency for custom error messages. How ever i am noticing that with the removal of this i am able to get case insensitivity of enums. But when i add this it expects exact string, In my API application start up how do i make the enums CASE INSENSITIVE
environment.jersey().enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS.toString()); or register does not work either

Related

How to use Scala Cats Validated the correct way?

Following is my use case
I am using Cats for validation of my config. My config file is in json.
I deserialize my config file to my case class Config using lift-json and then validate it using Cats. I am using this as a guide.
My motive for using Cats is to collect all errors iff present at time of validation.
My problem is the examples given in the guide, are of the type
case class Person(name: String, age: Int)
def validatePerson(name: String, age: Int): ValidationResult[Person] = {
(validateName(name),validate(age)).mapN(Person)
}
But in my case I already deserialized my config into my case class ( below is a sample ) and then I am passing it for validation
case class Config(source: List[String], dest: List[String], extra: List[String])
def vaildateConfig(config: Config): ValidationResult[Config] = {
(validateSource(config.source), validateDestination(config.dest))
.mapN { case _ => config }
}
The difference here is mapN { case _ => config }. As I already have a config if everything is valid I dont want to create the config anew from its members. This arises as I am passing config to validate function not it's members.
A person at my workplace told me this is not the correct way, as Cats Validated provides a way to construct an object if its members are valid. The object should not exist or should not be constructible if its members are invalid. Which makes complete sense to me.
So should I make any changes ? Is the above I'm doing acceptable ?
PS : The above Config is just an example, my real config can have other case classes as its members which themselves can depend on other case classes.
One of the central goals of the kind of programming promoted by libraries like Cats is to make invalid states unrepresentable. In a perfect world, according to this philosophy, it would be impossible to create an instance of Config with invalid member data (through the use of a library like Refined, where complex constraints can be expressed in and tracked by the type system, or simply by hiding unsafe constructors). In a slightly less perfect world, it might still be possible to construct invalid instances of Config, but discouraged, e.g. through the use of safe constructors (like your validatePerson method for Person).
It sounds like you're in an even less perfect world where you have instances of Config that may or may not contain invalid data, and you want to validate them to get "new" instances of Config that you know are valid. This is totally possible, and in some cases reasonable, and your validateConfig method is a perfectly legitimate way to solve this problem, if you're stuck in that imperfect world.
The downside, though, is that the compiler can't track the difference between the already-validated Config instances and the not-yet-validated ones. You'll have Config instances floating around in your program, and if you want to know whether they've already been validated or not, you'll have to trace through all the places they could have come from. In some contexts this might be just fine, but for large or complex programs it's not ideal.
To sum up: ideally you'd validate Config instances whenever they are created (possibly even making it impossible to create invalid ones), so that you don't have to remember whether any given Config is good or not—the type system can remember for you. If that's not possible, because of e.g. APIs or definitions you don't control, or if it just seems too burdensome for a simple use case, what you're doing with validateConfig is totally reasonable.
As a footnote, since you say above that you're interested in looking in more detail at Refined, what it provides for you in a situation like this is a way to avoid even more functions of the shape A => ValidationResult[A]. Right now your validateName method, for example, probably takes a String and returns a ValidationResult[String]. You can make exactly the same argument against this signature as I have against Config => ValidationResult[Config] above—once you're working with the result (by mapping a function over the Validated or whatever), you just have a string, and the type doesn't tell you that it's already been validated.
What Refined allows you to do is write a method like this:
def validateName(in: String): ValidationResult[Refined[String, SomeProperty]] = ...
…where SomeProperty might specify a minimum length, or the fact that the string matches a particular regular expression, etc. The important point is that you're not validating a String and returning a String that only you know something about—you're validating a String and returning a String that the compiler knows something about (via the Refined[A, Prop] wrapper).
Again, this may be (okay, probably is) overkill for your use case—you just might find it nice to know that you can push this principle (tracking validation in types) even further down through your program.

Preserving some null in Json4s

I'm trying to marshall a case class in json which is easy enough with json4s.
case class container(id: String, `type`: Option[String], things: List[???])
Json4s does an excellent job of omitting fields that are null. The issues is I'd like options at the top level of container to be preserved but everything in things (it's filled with nested options) to preserve these empty options and serve them as Nulls.
The follow question pointed me in the right direction Json4s ignoring None fields during seriallization (instead of using 'null')
But using implicit val f = DefaultFormats.preservingEmptyValues targets all of the case classes in scope. Is there anyway I can just target fields within things. I can't specifically target fields as there's quite a few and doing this could become unmanageable.
Thanks in advance

When to use Option in Scala and when not to

so Lets say I have some class:
case class Product(id: Int, name: String)
If I'm interfacing with some Java API or something and the possibility of either of those values being null is there then could I just write:
case class Product(id: Option[Int], name: Option[String])
If I wasn't interfacing with anything that has nulls as a concept then it would be fine to just stick with the first implementation right?
It seems a little annoying because I would have to write unit tests to test these things as well...
Thoughts would be much appreciated.
The question when to use Option should be more related to the fact that a value could be missing as opposed to a value might be mistakenly set to null.
To clarify, if you're worried that somehow the user of your library could set the id or name field to null, you should check for it in both version. Indeed Option itself doesn't give you any guarantee.
Furthermore using an Option where on a value that is not really optional is really misleading.
I usually use Option only to explicitly declare that a value might not be present and that is a valid state.
When it comes to interacting with Java I adopt the following 2 strategies depending if I'm providing the API or consuming it:
If I provide an API that is consumed by Java code I don't use Option, but instead use a little constructor wrapper which check that all parameters are not null and throw and IllegalArgumentException otherwise.
If I consume an API written in Java I do use Option wrapping all returned value so that my Scala code can handle these cases in a cleaner way.
Also you can use require to throw IllegalArgumentException, for example:
case class Product(id: Int, name: String){
require(name != null, "the name cannot be null")
}

Deserialization case class from ByteString

I send case class using:
tcpActor ! Tcp.Write(MyCaseClass(arg1: Class1, arg2: Class2).data)
Then I received:
case Tcp.Receive(data: ByteString)
Is there any simple way to match data on MyCaseClass without using low level java serializer?
I'm not sure if akka provides any facility for de-serialising binary data, I didn't find any so far. A good option would be to use scodec, which seems pretty good and quite popular in the scala ecosystem. By the way, where is that .data method you are using to serialise defined?
Your options:
1. Use Akka remoting to send the case classes directly
2. Use Java serialization
3. Use https://github.com/scala/pickling
4. Write your own message protocol to convert between case classes and byte strings
Choose what best fits your use case.

Using case classes in lifted Slick

In ScalaQuery it seemed to be possible to use case classes in table definitions. e.g. https://github.com/szeiger/scala-query/blob/master/src/test/scala/scala/slick/test/ql/MapperTest.scala#L26
But this syntax doesn't work in Slick. Specifically, the method <> is not available.
Is there a way to use case classes in lifted Slick without boilerplate mapping?
It still works. See https://github.com/slick/slick/blob/1.0.1/slick-testkit/src/main/scala/com/typesafe/slick/testkit/tests/MapperTest.scala . Be aware that you currently cannot map a single column, see https://github.com/slick/slick/issues/40 .
The error message you got could come from the component types of your projection not matching the component types of your case class. The <> method is added using an implicit conversion that is only applied if the types match.