Having issues with navigation in Webstorm?

Did your Ctrl+N or Ctrl+Shift+N or Ctrl+Shift+Alt+N stopped working properly in Webstorm (not considering all files, not finding all methods etc)? Then most probably there is an issue with Webstorm’s cache & needs to be invalidated. The solution is simple:

File -> Invalidate Caches .. -> Invalidate & Restart

Then the problem will be gone 🙂

Have a nice day!

How to navigate through usages in file with WebStorm

It’s quite useful sometimes to be able to navigate through the usages of a certain variable inside a file. For example, you find a method and you want to see where it’s being called, or a variable and see where it’s being used. With WebStorm it turns out it’s quite easy to do. You hit Ctrl + Shift + F7 and then you use F3 and Shift + F3 to navigate between usages.

Ctrl + Shift + F7    // Highlights all usages in file
F3 or Shift + F3     // Navigate forward or backward between usages

If you are interested in usages in other files as well, use Alt + F7 instead.

Alt + F7             // Finds usages inside the project

Dynamic Pinterest button

There are sometimes that you want to update the url or the media url of the Pinterest button dynamically. On Pinterest’s developer website there is nothing about it (weird!). I found a blog that suggests to remove & re-evaluate the pinit.js script, an approach that works but is very inefficient. I then by accident found on Github pinit.js uncompressed code and went through it & found out that it’s possible to update a button! Here is how you do it:

Step 1

You add a data-pin-build attribute to the script element that loads pinit.js and you give it a name, which will be the name of the method that you’ll be using for dynamically building Pinterest buttons (named build_pinterest_button in this example).

<script
  type="text/javascript"
  src="//assets.pinterest.com/js/pinit.js"
  data-pin-build="build_pinterest_button">
</script>

Step 2

Generate the new pinterest button (modifying the existing one might not work out because pinit.js replaces the button with a different one with a background image loaded from Pinterest’s servers). Then call the method you provided above on a parent container of the button (not on the button itself)

var $newButton = $('<div>')... //generate the new button
var $container = $(...)        //a parent container of the new button
build_pinterest_button($container[0]);  //re-build pinterest buttons inside container

And that’s it! You’ll get an update Pinterest button the same way as it does at the first time you load the script 🙂

If you run into any issues feel free to ask me (through comments below).

Problem with java and SSL Exception

For the last 2 weeks we had a problem with email sending on one of our servers (hosted on EC2). Our emails are sent through Amazon SES, which used to work great until a problem with SSL connections on Amazon SES came up. Since that time we started receiving complaints that some clients didn’t receive email confirmations. We investigated the issue (checked our error logs) and it seemed that we had to wait until Amazon fixes the issue (at least that’s what we thought). Amazon fixed the issue very quickly but we continued having problems. Today we found the solution by noticing that on one of the servers emails were being sent without any problem. And we noticed that on that server we had installed openjdk-6 instead of openjdk-7 as on the other server. Therefore we switched to openjdk-6 and it all started working normally!

Therefore, if you get an error similar to the one blow then we would recommend that you switch to openjdk-6 instead of openjdk-7.

Note: We tried configuring a completely new server (thinking that a SSL certificate needed to be updated) but didn’t help. Switching to openjdk-6 did the job 🙂

Here is the error:

play.core.ActionInvoker$$anonfun$receive$1$$anon$1: Execution exception [[MessagingException: Exception reading response]]
	at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:134) ~[play.play_2.9.1-play_2.9.1-2.0.6.jar:2.0.6]
	at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:115) ~[play.play_2.9.1-play_2.9.1-2.0.6.jar:2.0.6]
	at akka.actor.Actor$class.apply(Actor.scala:318) ~[com.typesafe.akka.akka-actor-akka-actor-2.0.2.jar:2.0.2]
	at play.core.ActionInvoker.apply(Invoker.scala:113) ~[play.play_2.9.1-play_2.9.1-2.0.6.jar:2.0.6]
	at akka.actor.ActorCell.invoke(ActorCell.scala:626) ~[com.typesafe.akka.akka-actor-akka-actor-2.0.2.jar:2.0.2]
	at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:197) ~[com.typesafe.akka.akka-actor-akka-actor-2.0.2.jar:2.0.2]
	at akka.dispatch.Mailbox.run(Mailbox.scala:179) ~[com.typesafe.akka.akka-actor-akka-actor-2.0.2.jar:2.0.2]
	at akka.dispatch.ForkJoinExecutorConfigurator$MailboxExecutionTask.exec(AbstractDispatcher.scala:516) ~[com.typesafe.akka.akka-actor-akka-actor-2.0.2.jar:2.0.2]
	at akka.jsr166y.ForkJoinTask.doExec(ForkJoinTask.java:259) ~[com.typesafe.akka.akka-actor-akka-actor-2.0.2.jar:2.0.2]
	at akka.jsr166y.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:975) ~[com.typesafe.akka.akka-actor-akka-actor-2.0.2.jar:2.0.2]
	at akka.jsr166y.ForkJoinPool.runWorker(ForkJoinPool.java:1479) ~[com.typesafe.akka.akka-actor-akka-actor-2.0.2.jar:2.0.2]
	at akka.jsr166y.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:104) ~[com.typesafe.akka.akka-actor-akka-actor-2.0.2.jar:2.0.2]
Caused by: javax.mail.MessagingException: Exception reading response
	at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1462) ~[javax.mail.mail-mail-1.4.jar:1.4]
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1260) ~[javax.mail.mail-mail-1.4.jar:1.4]
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370) ~[javax.mail.mail-mail-1.4.jar:1.4]
	at javax.mail.Service.connect(Service.java:297) ~[javax.mail.mail-mail-1.4.jar:1.4]
	at javax.mail.Service.connect(Service.java:156) ~[javax.mail.mail-mail-1.4.jar:1.4]
	at javax.mail.Service.connect(Service.java:105) ~[javax.mail.mail-mail-1.4.jar:1.4]
	at fly.play.ses.Ses$.sendEmail(Ses.scala:49) ~[nl.rhinofly.api-ses_2.9.1-api-ses_2.9.1-1.0.1.jar:1.0.1]
	at facade.Emails$.sendActivationEmail(Emails.scala:15) ~[easygogym_2.9.1-0.1.jar:0.1]
	at controllers.Users$$anonfun$sendActivationEmail$1.apply(Users.scala:116) ~[easygogym_2.9.1-0.1.jar:0.1]
	at controllers.Users$$anonfun$sendActivationEmail$1.apply(Users.scala:114) ~[easygogym_2.9.1-0.1.jar:0.1]
	at play.api.mvc.Action$$anon$1.apply(Action.scala:170) ~[play.play_2.9.1-play_2.9.1-2.0.6.jar:2.0.6]
	at play.core.ActionInvoker$$anonfun$receive$1$$anonfun$6.apply(Invoker.scala:126) ~[play.play_2.9.1-play_2.9.1-2.0.6.jar:2.0.6]
	at play.core.ActionInvoker$$anonfun$receive$1$$anonfun$6.apply(Invoker.scala:126) ~[play.play_2.9.1-play_2.9.1-2.0.6.jar:2.0.6]
	at play.utils.Threads$.withContextClassLoader(Threads.scala:17) ~[play.play_2.9.1-play_2.9.1-2.0.6.jar:2.0.6]
	at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:125) ~[play.play_2.9.1-play_2.9.1-2.0.6.jar:2.0.6]
	... 11 common frames omitted
Caused by: javax.net.ssl.SSLException: Server key
	at sun.security.ssl.Handshaker.throwSSLException(Handshaker.java:1274) ~[na:1.7.0_25]
	at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223) ~[na:1.7.0_25]
	at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868) ~[na:1.7.0_25]
	at sun.security.ssl.Handshaker.process_record(Handshaker.java:804) ~[na:1.7.0_25]
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016) ~[na:1.7.0_25]
	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312) ~[na:1.7.0_25]
	at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:882) ~[na:1.7.0_25]
	at sun.security.ssl.AppInputStream.read(AppInputStream.java:102) ~[na:1.7.0_25]
	at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:97) ~[javax.mail.mail-mail-1.4.jar:1.4]
	at java.io.BufferedInputStream.fill(BufferedInputStream.java:235) ~[na:1.7.0_25]
	at java.io.BufferedInputStream.read(BufferedInputStream.java:254) ~[na:1.7.0_25]
	at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:75) ~[javax.mail.mail-mail-1.4.jar:1.4]
	at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1440) ~[javax.mail.mail-mail-1.4.jar:1.4]
	... 25 common frames omitted
Caused by: java.security.spec.InvalidKeySpecException: Could not create EC public key
	at sun.security.pkcs11.P11ECKeyFactory.engineGeneratePublic(P11ECKeyFactory.java:169) ~[sunpkcs11.jar:1.7.0_25]
	at java.security.KeyFactory.generatePublic(KeyFactory.java:334) ~[na:1.7.0_25]
	at sun.security.ssl.HandshakeMessage$ECDH_ServerKeyExchange.(HandshakeMessage.java:1057) ~[na:1.7.0_25]
	at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:218) ~[na:1.7.0_25]
	... 36 common frames omitted
Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_DOMAIN_PARAMS_INVALID
	at sun.security.pkcs11.wrapper.PKCS11.C_CreateObject(Native Method) ~[sunpkcs11.jar:1.7.0_25]
	at sun.security.pkcs11.P11ECKeyFactory.generatePublic(P11ECKeyFactory.java:233) ~[sunpkcs11.jar:1.7.0_25]
	at sun.security.pkcs11.P11ECKeyFactory.engineGeneratePublic(P11ECKeyFactory.java:164) ~[sunpkcs11.jar:1.7.0_25]
	... 39 common frames omitted

Sublime Text 3 – new code browsing functionality

Just tried today for the first time Sublime Text 3!

It looks quite similar to Sublime Text 2 but it’s a bit faster (though ST2 was fast enough already for me) and has the following features that I fell in love with right away:

  1. Go to definition: Just put the cursor on any function and click F12 (in Windows or Linux). Then ST3 will take you to the function’s definition. If there are more than one, it’ll ask you which one to go to. It’s amazingly helpful feature and I’ll be using it all the time
  2. Jump back & Jump forward: This is the second best feature. Whenever you use Jump to definition (F12) you can use Jump back (Alt+Keypad minus) to get back to the code you were viewing before you jumped to definition. You can also Jump forward using Alt + Shift + Keypad minus.

I actually changed the key bindings to Alt+Left and Alt+Right which I find a bit more intuitive. You can do that by going to “Preferences” -> “Key Bindings – User” and setting the key bindings in a similar way like I did:

[
	{ "keys": ["alt+left"], "command": "jump_back" },
	{ "keys": ["alt+right"], "command": "jump_forward" }
]

Hope you will enjoy Sublime Text 3. It’s a really great editor!

Advantages of Play Framework in Scala over PHP down the road

Prior to switching to Play Framework (in Scala), I was using CakePHP and Zend Framework (in PHP). It has been a great time developing with CakePHP but as the time passes I see lots of disadvantages of using PHP. Here is a list of what comes to my mind:

1. Deployment & Maintenance

The biggest issue I have right now with PHP projects is maintenance. I’m simply too scared to get software updates for my webserver! Why? Because I’m afraid that a PHP package or a PEAR package will get updated and I’ll have to modify some old code that I don’t want to touch. I had the same problem trying to run an old PHP project on my new laptop. I just couldn’t! Got a bunch of errors cause my new laptop had a newer version of PHP and some PEAR packages (Amazon AWS SDK for example) changed quite a bit and I had to modify all around the code which wouldn’t work if I would publish it on the server that uses the old PEAR package.

If the project would be still active & it would worth the time, I would spend it. But not all projects do.

When I switched to Play Framework, all these issues were gone! All the libraries I’m using are downloaded automatically by SBT (Scala Build Tool), in the correct versions and there is no need to install any extra package on the server. The only requirement is to install JVM, which is usually not a big deal.

Also, when the new version of Play Framework came out, I didn’t have to update all my projects. Some projects will just stay with the old version of the framework. And they’ll work just fine because all the libraries of the framework are contained inside the project. Even the Scala language itself! I have right now two Play Framework projects running on the same server and one is using Scala 2.9 and the other one Scala 2.10. And they work just fine because I didn’t have to install Scala on the server. It’s contained in the packaged produced by play dist (the Play Framework command that packages the code).

2. Having control over the code

CakePHP and various other PHP frameworks make it very easy to get started. You usually run a scaffolding tool (web-based or command line) that generates your model, controller & views. Then you go around and you modify them and very quickly you have a working product! Authentication works without any extra code, you have an ACL (Access-Control-List) that allows only logged in users to access some pages and other pages are restricted only to admins. Everything seems fine! But what happens further down the road?

Further down the road things get a bit trickier:

  1. The auto-generated forms will not be sufficient and you’ll have to dive deep into the framework to find how to replace them with more verbose code that allows you to change some parameters
  2. The authentication will need some extra tweaking to redirect users to different urls depending on the user’s role and you’ll wonder how to do this since there is no code for authentication in your files!
  3. You’ll need some more precise authorization mechanism to prevent user’s from accessing each other’s data. And what will you do? Do you really want to put that “if” in every action in your controllers?
  4. At some point your interaction with the database will become a bit tricky. You’ll realise that you need to speed up some queries. And you open your model’s file and you see no code in it! Then you have to dive deep into the framework to learn the database mechanisms and how to use them. And also how to switch off all that magic that loads all the other dependent models on each request, where you don’t really need them.

With frameworks like Play Framework, things are a bit different. You start with an empty project. No scaffolding, no auto-generated codeno database magic. You need to learn how to access the database to create your models, then learn how to generate forms and then how to write the authentication and authorization code. It’s quite a bit of work telling the truth and might seem unproductive at the beginning. But further down the road things are a lot better:

  1. You can do any modifications you want on your forms. All the code is there and you know where to find the documentation.
  2. You can do all the tweaks you want on your authentication. The code is all there and you wrote it. Maybe you copy-pasted it but you still know where it is in your code.
  3. You can also modify the authorization mechanism and find really elegant ways of expressing it. There is absolutely no need to add that “if” to every action!
  4. You’ll also not have any problem with the database. You wrote all the queries and all the model’s code. It’s all there. Do any changes you need and speed up those slow queries.

Ok. That’s it about having control over the code. I think you got the point.

3. Refactoring

This subject is rather lame but it’s good to mention it. You already know that Scala is a compiled language where PHP is an interpreted language. Therefore if you modify some code in Scala you’ll get a bunch of compile errors before you’ll be able to run again your website. And Play Framework will show you exactly on which files and which line the error is. It’s a bit of trouble sometimes but once you fix the errors you have a bit more peace in your mind that the code is working as it should. You should still test it of course but at least you are not afraid that your client will open a page and see a syntax error!

With PHP things are different. You change the code and then you have to go around the website and see if everything works fine. You’ll tell me now that it’s the same with Scala but it’s not. With Scala you at least know that when a function is expecting a String, it’ll receive a String and not an array. But with PHP you don’t know that. You have to do more tests to make sure of that. So watch out with PHP.

Ok. That was lame. Compiled Vs Interpreted. We heard it 1000 times.

What I really wanted to say about refactoring is that with Play Framework and Scala you can do lots of simplifications on your code. What do I mean? Let me give you some examples that come to my mind:

  • In your actions for users you want to have quick access to the user model. Then you define a method def user(implicit req:Request[AnyContent]) that implicitly takes the request and returns you the user stored in the session. Then all around your actions you can easily access your current user.
  • You can simplify your validation code and create really readable and elegant code. See this blog entry about it.
  • You can create a toJson method on your models that produces a json version of your object with the values you want to include by combining information from other models etc.
  • Simplify your models by creating a base model with methods like find, update, insert, delete etc. I know these are provided by the PHP frameworks but here you can easily modify them to optimize them whenever you want.

It’s a lot more things than what I wrote here but I can’t recall all of them right now. I hope you got the point.

Conclusion

Since I switched to Play Framework (in Scala) from Cake PHP a year and a half ago, I have enjoyed coding a lot more! I’m already quite efficient with Play and I can find endless way to simplify my code and make it really neat and readable. And deployment is going really well! No issues with the server updates, websites run super fast and barely having any downtime. I’m really happy with Play and Scala and I really want to see more people using it! Not only because it’s fun & very productive environment but I also want it to be easier to find people to work with on Play projects 🙂 The more people get to know Play and Scala the less arguments I’ll have to bring in to convince them to use it on a new project with me 🙂

Ok .. I wrote a quite a lot today! Need to get back to work!

Try, the new monad in Scala 2.10

Today I tried for the first time Scala’s Try monad. I used it twice already and I’m sure I’ll use a lot more times!

Here is how I used it the first time. I wanted to parse some CSV data into a sequence of case classes. And of course, with input data you never know what can go wrong. I didn’t really want to handle the error, I just wanted to know if it was parsed correctly or not. Therefore I used an Option to return either Some(result) or None.

Here is the code for the attempt with Option:

def parseCSV(csv : String) = {
  try {
    Some {
      csv.split("\n").map { line =>
        val tokens = line.split(";")
        ActivityData(tokens(0).toLong, tokens(1).toInt, tokens(2).toInt, tokens(3).toLong)
      }
    }
  } catch {
    case _ : Throwable => None
  }
}

A bit complicated isn’t it? Using this function is cool (just as with every other Option) but actually reading it is painful. It’s just too messy with that try catch. Is there a better way of doing this?

Well, there comes the Try monad from scala.util package to save the situation!

def parseCSV(csv : String) = Try {
  csv.split("\n").map { line =>
    val tokens = line.split(";")
    ActivityData(tokens(0).toLong, tokens(1).toInt, tokens(2).toInt, tokens(3).toLong)
  }
}

Look at this! Wow! This is neat! Just surround your code with Try and that’s it!

And the best part, you can use it exactly the same way as you would use the Option monad (dah .. that’s what are monads all about).

parseCSV(csvdata).map { entries =>
  //do something with the data
}.getOrElse {
  BadRequest("Invalid CSV Data")  //this is Play Framework specific (returns a 400 HTTP response with a message)
}

Note: For those who are wondering how does this work, the Try monad returns Success(something) if everything was calculated without any exceptions and Failure(error) if an error was thrown while executing the argument of Try().

Note (deep): Try takes its argument by-name (not by-value), therefore it can execute it within a try, catch the exception and return either Success or Failure. Isn’t Scala a super powerful awesome language? Yes it is!