hisham hm

🔗 Enable JSON conversion in MOXy to avoid 415 Unsupported Media Type

If you follow the “Getting Started” tutorial for Jersey (an API for writing REST apps in Java), you’ll get a nice working “Hello World” example called “simple-service”. However, if you try to extend it to use JSON using MOXy’s advertised auto-coversion of JSON into Java objects, you’ll get a “415 Unsupported Media Type” HTTP response if you don’t do it right.

Things that can cause 415 Unsupported Media Type:

Not having MOXy enabled in your pom.xml

Make sure this is present and uncommented in your pom.xml file:

      <dependency>
         <groupId>org.glassfish.jersey.media</groupId>
         <artifactId>jersey-media-moxy</artifactId>
      </dependency>

Not using @Consumes and @Produces annotations

Make sure they are set in your method:

   @POST
   @Consumes("application/json")
   @Produces("application/json")
   public string postIt(MyObject obj) {

Not sending Content-Type headers

Here’s an incantation of curl that does the right thing for testing a POST:

curl -v -H "Content-Type: application/json" -X POST -d '{"name":"hisham"}' http://localhost:8080/myapp/myresource

Not initalizing the JSON feature in MOXy

This is the default initalization given in the “simple-service” minimal example:

   public static HttpServer startServer() {
      // create a resource config that scans for JAX-RS resources and providers
      // in com.example package
      final ResourceConfig rc = new ResourceConfig().packages("com.example");

      // create and start a new instance of grizzly http server
      // exposing the Jersey application at BASE_URI
      return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
   }

and this is how you should extend it:

   public static HttpServer startServer() {

      final MoxyJsonConfig moxyJsonConfig = new MoxyJsonConfig();
      final ContextResolver jsonConfigResolver = moxyJsonConfig.resolver();

      // create a resource config that scans for JAX-RS resources and providers in given package
      final ResourceConfig rc = new ResourceConfig().packages("com.example")
                                                    .register(MoxyJsonFeature.class)
                                                    .register(jsonConfigResolver);

      // create and start a new instance of grizzly http server
      // exposing the Jersey application at BASE_URI
      return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
   }

Once all those are fixed...

Now you can add a method to MyResource such as:

   @POST
   @Consumes("application/json")
   @Produces("application/json")
   public MyObject postIt(MyObject obj) {
      obj.name += " world";
      return obj;
   }

given that you have a class like

   public class MyObject {
      public String name;
   }

and the conversion to-from JSON will work automagically:

curl -v -H "Content-Type: application/json" -X POST -d '{"name":"hisham"}' http://localhost:8080/myapp/myresource
> POST /myapp/myresource HTTP/1.1
> Host: localhost:40409
> User-Agent: curl/7.42.1
> Accept: */*
> Content-Type: application/json
> Content-Length: 17
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Date: Mon, 14 Dec 2015 18:23:46 GMT
< Content-Length: 23
<
{"name":"hisham world"}

🔗 Os hábitos do software livre…

Li um post de um amigo no Facebook e deu vontade de editar corrigindo um errinho de português (reflexo de ler a Wikipedia, onde eu posso fazer e faço isso).

Aí pensei que como o texto está no nome dele então não seria legal editar direto, mas sim editar uma cópia e enviar um “pull request” pra ele onde ele pudesse ver as mudanças e aceitá-las, atualizando o próprio post em um click (como acontece no Github, site de compartilhamento de código de software livre onde tenho meus projetos). Infelizmente o Facebook não oferece esse recurso.

Por que o mundo em geral não é mais como o mundo do software livre? A Wikipedia tá aí pra mostrar que, se você der pras pessoas ferramentas para atuar colaborativamente, um número suficiente de pessoas vai usá-las de modo a produzir resultados fantásticos.

🔗 Sobre a “nova economia” das empresas da internet

Vi essa imagem no Facebook:

Roteiro comum a todos esses:

  1. consiga uma graninha de de venture capital (seed money)
  2. use esse dinheiro para construir uma infraestrutura (site, aplicativo) para prover um serviço de middle-man para facilitar acesso centralizado a alguma coisa qualquer que esteja distribuída
  3. segundo round de investimento: (Series A round) apresente essa infra aos investidores e levante alguns milhões de venture capital, para sustentar a próxima fase [*]
  4. ofereça o serviço de middle-man gratuitamente à população, dando a eles a coisa com o preço do mercado (ou a prejuízo, vide: dumping), mas com conveniência maior (afinal, centralizado é sempre mais conveniente que distribuído)
  5. com a tendência natural de network effect, o serviço acumula usuários a ponto de “todo mundo estar nele” (network effect)
  6. uma vez que a fase anterior andou suficientemente, a base de usuários (especialmente, do lado dos usuários que provê conteúdo comercialmente à plataforma, os “parceiros”) estará “presa” à sua rede (ie, com esforço investido demais nela para migrar para outra [ex: likes na página da sua empresa no Facebook, pontuação de recomendações no Uber ou Airbnb], vide: vendor lock-in), aí pode “monetizar” em cima deles à vontade, eles não têm pra onde ir.

Resumindo, aparentemente a grande sacada do emprendedorismo moderno é construir um monopólio virtual como atravessador pela internet.

[*] essa fase funciona mais fácil se você estiver na grande San Francisco**
[**] preferencialmente se você já tiver passado pela fase 1 em San Francisco também***
[***] e especialmente se tiver sido por alguma encubadora de lá, tipo YCombinator****
[****] suas chances de entrar na YCombinator aumentam se você vier de alguma universidade tipo MIT ou Caltech

🔗 Economia: tudo está ligado

Não existe essa de tentar entender a economia do Brasil sem entender a do mundo.

Depois da crise de 2008, o Primeiro Mundo apertou o cinto e os especuladores jorraram dinheiro nos mercados emergentes, que não aprenderam a lição com os primos ricos e se endividaram loucamente. Mas não consigo olhar essa tabela abaixo e não lembrar dos telejornais lá por 2012 reclamando que o PIB do Brasil não conseguia crescer a ritmo chinês (lembram do papo do “pibinho”?)… Aí a gente olha essa tabela e pensa: “a que custo?”

Achar que “o PT fez isso” é tão ingênuo quanto achar que a onda de privatizações na década de 1990, que foi da Europa à África à América Latina, “foi obra do PSDB”.

A derrubada do preço do petróleo foi uma cartada de mestre pra desestabilizar os BRICS, que foram pegos com as calças na mão por terem entrado na euforia do endividamento fácil (mesmo canto da sereia que atingiu o Primeiro Mundo em 2008). E alguém se surpreende que a Rússia, país mais atingido do grupo agora, resolveu agora mandar a sua força aérea pro Oriente Médio?

🔗 Generalized nullable operators

Today I was writing some Lua code and had to use something like this for the millionth time:

logger:fine("my message " .. (extra_data or ""))

Since operators in Lua fail when applied to null (and thankfully don’t do wat-eseque coercions), whenever I want to perform an operation on a value that may be null, I have to add the neutral element of the operation as a fall back:

print(a + (b or 0))
print(x * (y or 1))

This got me thinking of null-conditional operators such as ?. that some other languages such as C# have.

Then I wondered: wouldn’t it be nice if “?” could be a modifier to any operator?

Creating null-checking operators

Here’s the initial sketch of the idea: in case of a “nullable operator”, just cancel the operation when given a null operand: i.e., return the left-hand value in case the right-hand value is null.

Or, expressed in Haskell, here’s a function “rightCheckNullable” that takes a normal operator and converts it to a nullable version checking the right-hand value (”nullable types” are represented as “Maybe” types in Haskell):

rightCheckNullable :: (a -> b -> a) -> (a -> Maybe b -> a)
rightCheckNullable fn = a b ->
   case b of
   Just x  -> fn a x
   Nothing -> a

Let’s create some nullable operators:

(+?) = rightCheckNullable (+) -- nullable addition
(*?) = rightCheckNullable (*) -- nullable multiplication
(++?) = rightCheckNullable (++) -- nullable concatenation

And give them a spin:

main =
   let
      v1 :: Float
      v1 = 123

      v2 = Nothing

      v3 :: Maybe Float
      v3 = Just 456
   in
      do
         print $ show (v1 +? v2) -- prints 123.0
         print $ show (v1 +? v3) -- prints 579.0
         print $ show (v1 *? v2) -- prints 123.0
         print $ "hello" ++? Just "world" -- prints helloworld
         print $ "hello" ++? v2 -- prints hello

With something like the above, instead of a + (b or 0) and x * (y or 1), one could write simply:

print(a +? b)
print(x *? y)

This could give back some of the terseness we have when null auto-coerces to other types, without surprises with various operations. In JavaScript, null coerces to 0 when it is an integer, which gives us a proper neutral element for addition but not for multiplication.

Null-checking in C#

Note, however, that my choice of picking the right-hand value and checking the left-hand value only was arbitrary (though it works well for the examples above).

In C#, operations on nullable types are always lifted: the operators of the original types are extended with a check where, if either of the arguments is null, the result of the operation is null.

In Haskell, this transformation would be the following, taking a function that goes from a’s to b’s producing c’s, and producing an equivalent function that goes from Maybe a’s to Maybe b’s producing Maybe c’s:

bothCheckNullable :: (a -> b -> c) -> (Maybe a -> Maybe b -> Maybe c)
bothCheckNullable fn =
    ma mb ->
      case ma of
         Nothing -> Nothing
         Just a ->
            case mb of
               Nothing -> Nothing
               Just b -> fn a b

(In Haskell, you don’t have to actually write this function, since can use Control.Applicative.liftA2, a generalization of the above, to get the same result)

Checking the left-hand value

This makes me think that my “nullable operator modifier” could be aplied to either side (or both). Note that the syntax for null-conditional in C# is already ?., with the question-mark on the left-hand side, since the value being checked for nullity is the left-hand one. We don’t want x?.y to return y when x is null, though. A more sensible semantics for left-hand ? would be a “short-circuiting” one:

leftCheckNullable :: (a -> b -> c) -> (Maybe a -> b -> Maybe c)
leftCheckNullable fn = a b ->
   case a of
   Just x  -> fn x b
   Nothing -> Nothing

The flood gates are open!

There is still an asymmetry here, as rightCheckNullable is the only one that returns the “other value” when one of them is null.

In fact, we could have six versions of the conversion function: right-check, both-check, left-check, each of them returning the “other value” (as I did with +?) or null. If we called the C#-like version +??, this means addition could be modified into: +?, ?+, ?+?, +??, ??+, ??+??.

(And there could be two more variants of course, ?+?? and ??+?, but coming up with a realistic example using them would be a nice exercise in creative coding.)

But would it make sense to have so many modifiers?

Well, for one, instead of writing this

logger:severe("Error: connection failed" .. (details and (" - details: "..details) or ""))

we could write something like:

logger:severe("Error: connection failed" ..? (" - details: " ..?? details))

I know this is a step into the world of APL, and I’m not arguing this is a great or even good idea, but it was fun to think about, so I thought I’d share.


Follow

🐘 MastodonRSS (English), RSS (português), RSS (todos / all)


Last 10 entries


Search


Admin