Powered By Blogger

sábado, 31 de agosto de 2013

Estados Unidos mantuvo 231 operaciones de ciberespionaje en 2011

Barksdale Air Force Base, LA -- Captain Jason Simmons, left, and Staff Sgt. Clinton Tips update anti-virus software for Air Force units to assist in the prevention of cyberspace hackers at Barksdale AFB. The Air Force is setting up a Cyberspace Command soon and these Airmen are the operators and the ground floor. (U.S. Air Force photo/Technical Sgt. Cecilio Ricardo) (released)

Nuevas filtraciones de Edward Snowden publicadas por The Washington Post, detallan el programa de ciberespionaje que mantienen los Estados Unidos a nivel internacional.

Hace apenas un día fueron publicados una serie de documentos filtrados por Edward Snowden, el conocido responsable de revelar ante el mundo el programa de espionaje PRISM, que prometían detallar todo el presupuesto dedicado al espionaje que maneja la NSA y la CIA en Estados Unidos, el cual alcanza los 52 mil millones de dólares. Aún así, la información no fue revelada por completo, y hoy The Washington Post comienza a liberar más detalles incluidos en estos documentos filtrados por Edward Snowden.

La información que The Washington Post da a conocer hoy, menciona que nada más durante el año 2011 Estados Unidos llevó a cabo 231 programas de ciberespionaje internacional, detallando así la manera en la que el país se infiltra mediante programas, software y agentes especializados, en computadoras, servidores y en general, territorios de interés o de "carácter sensible", como los cataloga el gobierno norteamericano.

Irán, China, Corea del Norte y Rusia son prioridad para el programa de ciberespionajeEl programa ciberespionaje estadounidense cuenta con un presupuesto anual de más de mil millones de dólares, y está dedicado a infiltrarse en docenas de miles de computadores en países de "interés". Entre estos, los estados prioritarios son: Irán, China, Corea del Norte y Rusia. Bastante curioso que este último país esté incluido como prioridad en la vigilancia norteamericana, cuando se supone que actualmente ambos países llevan buenas relaciones, y muchos convenios.

GENIE y el programa TURBINE

Pero sin duda lo más alarmante de esta información es lo referente al programa llamado TURBINE, un proyecto que lleva a cabo una división de la NSA (denominada "TAO") que se especializa en el desarrollo de software autónomo dedicado al ciberespionaje.

Actualmente, más de 80 mil computadores y servidores han sido infiltrados con lo que podríamos llamar un "agente dormido", un software oculto que es inmune a actualizaciones de sistema y cualquier Firewall o antivirus rutinario que pudiera ser instalado en el computador víctima. Sin embargo, la vigilancia de estos dispositivos depende en gran parte de empleados o agentes de la NSA, TURBINE soluciona esta dependencia con un software inteligente que, sencillamente, puede espiar y actuar por sí solo, enviando a su nave nodriza (su base de control en Estados Unidos) la información que crea de interés y recopile.

El nuevo software que desarrolla TAO sería parte del proyecto GENIE, nombre que lleva este programa de espionaje cibernético masivo llevado a cabo por la NSA. La idea es que en un futuro (bastante cercano), TURBINE logre ser completamente autónomo y no dependa de agentes externos, a tal escala que no solo podría identificar y recopilar información en los computadores infiltrados (¿o infectados?), sino también identificar comunicaciones por voz de interés e incluso pudiera prevenir ataques que se generen desde esos servidores.

Será una Botnet de espionaje perfecta.

Es irónico que apenas hace unas horas la NSA anunciara que comenzará a dar informes de transparencia sobre sus acciones, mientras que estos documentos revelan una increíble cantidad de programas de vigilancia y espionaje que, de otra forma, jamás conoceríamos. Y mientras hablamos de software autónomos de espionaje y vigilancia, solo puedo pensar Skynet y el futuro.







Reglas de etiqueta en juego online que deberías cumplir si no quieres que te odien

!Joffrey Baratheon

Si Joffrey Baratheon tuviera una consola y acceso al juego online, sería un idiota. Y tú no quieres ser como Joffrey, así que es mejor que sigas estas reglas de etiqueta.

El juego online ha evolucionado mucho desde sus inicios, pero hay vicios que permanecen inmutables. De las primeras partidas de Diablo, Starcraft o Counter Strike a lo que inevitablemente ocurrirá cuando llegue a las tiendas GTA V. Los mismos seres y actitudes indeseables han estado presentes desde las primeras generaciones y seguirán en las venideras. ¿Por qué? Porque es divertido. El mundo online no tiene tantas reglas, así que, ¿por qué deberíamos imponerlas? Pero tampoco pasa nada por tratar de civilizar un poco el mundillo.

Para qué negarlo: todos hemos sucumbido alguna vez. Está bien, no pasa nada por dejarse seducir por el lado oscuro alguna que otra vez. Pero hay una serie de reglas de etiqueta en el juego online que deberías tener en cuenta para no ser odiado por todo el mundo. Porque se puede tener clase jugando en ropa interior a las 2 de la madrugada.

Saber perder

Esto es básico y aplicable a todo lo que se hace en la vida. Hay que aceptar la derrota con elegancia y caballerosidad, dar la mano y seguir adelante con orgullo. Aunque por dentro mueras un poco y sólo pienses en la venganza (más adelante hablaremos de ello).

Aunque mueras por dentro, acepta la derrotaEspecialmente reprochables son todo tipo de estrategias de mal perdedor para hacer que la partida pierda interés o directamente termine. Abandonar la partida cuando todo está perdido es el octavo pecado capital y está considerado crimen contra la humanidad por la ONU, la OTAN, la Alianza, el Imperio Galáctico y el ayuntamiento de Pawnee. No lo hagas.

De todos modos, irse no es la única forma de demostrar que no sabes perder. En el juego online hay muchas formas de hacer que el ganador se arrepienta de haber sido superior. En los juegos de fútbol, por ejemplo, pasar el balón entre el portero y los defensas cuando el partido está perdido es una costumbre que hace llorar a Cantona. Joga bonito, no seas sucio.

Saber ganar

Es curioso, pero a veces es casi más difícil saber asumir una victoria que una derrota. El juego online tiene la ventaja de que tu oponente no tiene por qué ver la celebración, así que desconecta el micrófono cuando des gritos de alegría. Y, como decíamos antes, si has conseguido vengarte no hace falta que lo proclames a los cuatro vientos; recuerda que una venganza implica una derrota anterior.

De todos modos, aquí es más difícil ser un caballero. Las reglas de etiqueta del juego online establecen que no debes pasarte con la celebración, pero tampoco es elegante quedarte corto. Si te ha costado ganar no hagas como que no.

Eso sí, estas reglas son para el contacto con desconocidos. Con amigos la competición y la competencia son más sanas cuanto más rastreras son las puñaladas y más encarnizadas las disputas. Si es tu amigo, conoces sus puntos débiles. Úsalos.

No abuses (mucho) de los que no saben

En tu primera partida de Super Mario te movías más que Steve Ballmer jugando con Kinect en una conferencia de desarrolladores, así que no olvides que nadie nace sabiendo. En cualquier juego online hay un proceso de aprendizaje por el que hay que pasar para convertirse en un experto y no es justo que la tomes con los que no saben sólo por eso. Que sepas que meterse con los más débiles es un signo de psicopatía.

No obstante, siempre puedes dar alguna pequeña lección gratuita y enseñar a los más ingenuos que el mundo es duro y los escenarios de Call of Duty, más. Tampoco pasa nada si se lo repites para que lo entiendan. Una tercera demostración ya es abusar.

Ten elegancia

Lo visto hasta ahora no sirve de nada si no tienes elegancia. No digas palabrotas si no hace falta —no seré yo quien diga que nunca hace falta— y trata de no aludir a cosas tan personales como la religión, la familia, el aspecto físico, la condición sexual o los cereales favoritos. Si lo haces, comenzarás una discusión sin sentido y terminarás hablando de Hitler.

No siempre hace falta utilizar groseríasDe todos modos, si sientes la necesidad irrefrenable de ponerte personal, recuerda que la bofetada que más duele es la que se da con guante de seda. Bueno, probablemente dolería mucho más con un guante metálico con púas y tal vez algo de veneno, pero con un guante de seda duele por dentro.

Lo mismo ocurre con tu forma de jugar. Humillar al adversario tiene gracia cuando es algo puntual y cuando se trata de un rival con un nivel parecido. Si quieres quedar bien con un regate estiloso, un adelantamiento imposible o un asesinato con cuchillo, tiene que suponer un reto.

No seas repelente

Todas estas reglas de etiqueta en juego online se resumen en este punto. No seas repelente. ¿O es que acaso has encontrado conoces a alguien que diga que Joffrey Baratheon es su personaje favorito de Canción de Hielo y Fuego? No, la gente admira a Jaime, Tyrion, Arya, Jon Nieve o incluso al Perro.

Y es que si Joffrey tuviese una consola o un ordenador en el trono de hierro, no hay duda de que campearía, gankearía, haría trampas y se comportaría como un idiota. Él tiene la excusa de que jugar en una silla hecha de espadas pondría de mal humor a cualquier, pero tú no. Así que no seas Joffrey.







viernes, 30 de agosto de 2013

Todo lo que debes saber sobre la secuenciación de ADN

Stuart Caie (Flickr)

En el futuro, quizás podemos contar con nuestra información genética incluida en nuestria historia clínica. Y es que los avances en secuenciación del ADN ofrecen grandes posibilidades en medicina, ¿sabes cuáles son?

Uno de los avances más importantes en el desarrollo de la medicina personalizada es, sin duda, la capacidad leer lo que dicen nuestros genes. En otras palabras, realizar la secuenciación de ADN ha permitido no solo conocer nuestra información genética, sino también predecir cuál es el riesgo de padecer ciertas enfermedades o incluso, adaptar ciertos tratamientos en función de nuestro genoma.

Y es cuando se completó el Proyecto Genoma Humano, allá por 2003, nadie pensaba que los avances en la secuenciación de ADN iban a avanzar tantísimo. Esto ha sido posible gracias a la investigación genética, que ha permitido nuevas tecnologías punteras e innovadoras en la secuenciación de ADN.

Prueba de ello es que el Archon Genomics X PRIZE Competition, galardón que buscaba premiar a la compañía que consiguiera la secuenciación de ADN por menos de 1.000 dólares, ha sido suspendido. En cierta manera, la competitividad que existía entre varias empresas por leer las letras de un solo genoma humano de la forma más barata y rápida posible, podía conducir a problemas futuros. Y es que la secuenciación de ADN, además de eficiente, ha de ser sobre todo fidedigna, debido a los potenciales usos en medicina.

Fred Sanger, pionero en la secuenciación de ADN

El primer científico que desarrolló una técnica para poder leer nuestra información genética fue Frederick Sanger, que recibió el Premio Nobel de Química en dos ocasiones (siendo la cuarta persona en el mundo en conseguirlo, tras Marie Curie, Linus Pauling y John Bardeen).

Su trabajo como bioquímico en la Universidad de Cambridge posibilitó el desarrollo del 'método Sanger' en 1975. Esta fue la primera técnica que tuvieron los investigadores para leer ADN. Pero, ¿cómo se llevaba a cabo? La tecnología desarrollada por Fred Sanger consistía en copiar el proceso natural de replicación de nuestro ADN, y fue fundamental para el desarrollo del Proyecto Genoma Humano.

Años antes de que se consiguiera completar la secuenciación de ADN de un genoma humano, Sanger ya utilizó su pionera técnica para leer el genoma del bacteriófago Phi-X174 en 1977. El trabajo, publicado en la Revista Nature marcaría sin duda un hito histórico en la historia de la genética y la medicina.

Maxam y Gilbert: la secuenciación química

Casi al mismo tiempo que Fred Sanger, dos investigadores (Allan Maxam y Walter Gilbert) desarrollaron un método alternativo para la secuenciación de ADN. De hecho, sus primeros resultados fueron publicados antes que el artículo de Nature de Sanger, pero a la postre la mayor parte de laboratorios elegirían el método de este último debido a su alta eficiencia.

A pesar de ello, uno de los pioneros de la secuenciación química, Walter Gilbert, también vio reconocido su trabajo, al compartir con Sanger el Premio Nobel de Química en 1980. Y es que la determinación de nucleótidos de una cadena, o lectura de nuestra información genética, creció a pasos gigantescos con el trabajo de estos investigadores.

Secuenciación masiva: ¿hacia dónde vamos?

Los problemas asociados al método de Sanger para realizar la secuenciación de ADN eran variados, aunque como hemos dicho, ha tenido una importancia crucial en la historia de la ciencia. Sin embargo, los investigadores cada vez buscan leer el genoma de manera más rápida y barata, como comentábamos antes. Para ello no 'podían permitirse' hacer la secuenciación del ADN 'a trozos', sino que sería mejor tratar de realizar la lectura de los genomas de manera completa.La secuenciación masiva permitirá el despegue de la medicina personalizada

Con este objetivo, han nacido las conocidas como técnicas de secuenciación masiva, más conocidas en inglés como next-generation sequencing (NGS). Como explican en este artículo sobre secuenciación del ADN, "las nuevas plataformas se distinguen por su capacidad de secuenciar millones de fragmentos de ADN de forma paralela a un precio mucho más barato por base".

Esta secuenciación de ADN de forma masiva puede llevarse a cabo mediante diferentes herramientas comerciales: Roche/454, Illumina, Life Technologies, Pacific Biosciences, Ion Torrent y Oxford Nanopore. En solo siete años, cambiar de la tecnología clásica de lectura de genomas a la de nueva generación permitió el ahorro de casi 5.000 dólares por genoma, como cuentan en esta conferencia sobre análisis genómico.

El avance de estas nuevas tecnologías de secuenciación del ADN permitirán grandes avances en medicina. Por ejemplo, podremos tratar las enfermedades con farmacogenómica, adaptando las terapias a los pacientes según su información genética. Esto reducirá los efectos secundarios asociados a los tratamientos, y permitirá el desarrollo de una medicina mucho más personalizada, como también explicábamos en esta entrevista al Dr. Josep Antoni Ramos Quiroga.

Más posibilidades, como en el caso de la secuenciación del ADN prenatal, marcan las fronteras de la futura revolución genómica. Quizás en la próxima década no sea tan raro contar con nuestra información genética en nuestra historia clínica personal. Ello significaría que por fin los senderos de la genómica y la medicina se han encontrado, y avanzan caminando juntas.







[Mecánica de fluidos I] Viscosidad

Nos encontramos ya entrando en la recta final de nuestro bloque introductorio a la Mecánica de fluidos. Después de establecer las bases más clásicas de esta disciplina en los primeros siete capítulos, en el último empezamos a desviarnos hacia cosas algo más complicadas hablando de la tensión superficial. Como seguro que recuerdas, la razón de [...]

Xdebug – Professional PHP Debugging

Our Agenda

  1. Introduction to the topic.
  2. Downloading and installing Xdebug on your local machine (Mac OS X 10.6.6+, MAMP 2.1.1).
  3. Integrating with PhpStorm.
  4. Practice debugging.


What You Will Need

  • A Mac running Mac OS X 10.6.6+.
    • If you are on 10.8.X you may need to install XQuartz as Apple removed X11.
    • If you are on Windows, the whole process is somewhat easier, just hit Google for more details.
  • Apple Xcode 4.6 (free on the Mac App Store).
    • Command Line Tools.
  • Homebrew.
  • A terminal app of your choice.
  • PhpStorm 5+ (many other IDE's will work as well).

What Is Xdebug?

Well, technically, Xdebug is an extension for PHP to make your life easier while debugging your code. Right now, you may be used to debugging your code with various other simple solutions. These include using echo statements at different states within your program to find out if your application passes a condition or to get the value of a certain variable. Furthermore, you might often use functions like var_dump, print_r or others to inspect objects and arrays.

What I often come across are little helper functions, like this one for instance:

function dump($value) {      echo '<pre>';      var_dump($value);      echo '</pre>';  }  

The truth is, I used to do this too, for a very long time actually.

The truth is, I used to do this too, for a very long time actually. So what's wrong with it? Technically, there is nothing wrong with it. It works and does what it should do.

But just imagine for a moment, as your applications evolve, you might get into the habit of sprinkling your code all over with little echos, var_dumps and custom debuggers. Now granted, this isn't obstructive during your testing workflow, but what if you forget to clean out some of that debug code before it goes to production? This can cause some pretty scary issues, as those tiny debuggers may even find their way into version control and stay there for a long time.

The next question is: how do you debug in production? Again, imagine you're surfing one of your favorite web-services and suddenly you get a big array dump of debug information presented to you on screen. Now of course it may disappear after the next browser refresh, but it's not a very good experience for the user of the website.

Now lastly, have you ever wished to be able to step through your code, line by line, watch expressions, and even step into a function call to see why it's producing the wrong return value?

Well, you should definitely dig into the world of professional debugging with Xdebug, as it can solve all of the problems above.


Configuring MAMP

I don't want to go too deep into the downloading and installation process of MAMP on a Mac. Instead, I'll just share with you that I'm using PHP 5.4.4 and the standard Apache Port (80) throughout this read.


Your First Decision

A quick note before we start with building our own Xdebug via Homebrew: If you want to take the easiest route, MAMP already comes with Xdebug 2.2.0. To enable it, open:

/Applications/MAMP/bin/php/php5.4.4/conf/php.ini

with a text editor of your choice, go to the very bottom and uncomment the very last line by removing the ;.

The last two lines of the file should read like this:

[xdebug]  zend_extension="/Applications/MAMP/bin/php/php5.4.4/lib/php/extensions/ no-debug-non-zts-20100525/xdebug.so"  

Now if you're asking yourself:

"Why would I want to choose a harder way than this one?"

And my answer to that is, it is never a mistake to look beyond your rim and learn something new. Especially as a developer these days, throwing an eye on server related stuff will always come in handy at some point in time. Promised.


Install Xcode and Command Line Tools

You can get Apple Xcode for free off of the Mac App Store. Once you've downloaded it, please go to the application preferences, hit the "Downloads" tab and install the "Command Line Tools" from the list.


Install Homebrew

Homebrew is a neat little package manager for Mac OS X which gets you all the stuff Apple left out. To install Homebrew, just paste the following command into your terminal.

ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go)"  

On a Mac, Homebrew will be the most convenient way to install Xdebug. On Linux however, compiling it yourself is the best way to go; which is not that easy on a Mac.

Tip: Windows users just need to download the *.dll file from Xdebug.org, put it into the XAMPP folder and add the path to their php.ini file.

As a PHP developer, you should from now on be aware of Jose Gonzalez's "homebrew-php" Github repo, which holds a lot of useful "brews" for you. If you've ever asked yourself how to install PHP 5.4 manually, you are right there.

Now if you get into any trouble while installing Homebrew, check out Jose's Readme.

To complete our Homebrew excursion, we want to "tap" into Jose's brewing formulae by executing the following commands within your terminal application:

brew tap homebrew/dupes  

This will get us some dependencies we need for Jose's formulae.

brew tap josegonzalez/homebrew-php  

Done! Now we should be ready to install Xdebug the comfy way, on a Mac.


Install Xdebug

Back in your terminal application, please execute:

brew install php54-xdebug  

If you are on PHP 5.3, just replace the "4″ with a "3″ ;)

The installation will take some time. After it's done, you'll see a little beer icon and some further instructions which you can ignore.

So what just happened? Homebrew downloaded all the files including their dependencies and built them for you. As I've already told you, compiling yourself on a Mac can be a hassle. At the end, we got a freshly compiled xdebug.so located at /usr/local/Cellar/php54-xdebug/2.2.1/.

Attention: Please note that Homebrew will install PHP 5.4 to your system during the process. This should not influence anything as it is not enabled on your system.

To finally install Xdebug, we just need to follow a few more steps.

Change directory (cd) to MAMP's extensions folder:

cd /Applications/MAMP/bin/php/php5.4.4/lib/php/extensions/no-debug-non-zts-20100525  

You can re-check the path by looking at the last line of /Applications/MAMP/bin/php/php5.4.4/conf/php.ini, as this is where we are going.

Backup the existing xdebug.so just in case:

mv xdebug.so xdebug.so.bak  

Then copy your Homebrew Xdebug build:

cp /usr/local/Cellar/php54-xdebug/2.2.1/xdebug.so /Applications/MAMP/bin/php/php5.4.4/lib/php/extensions/no-debug-non-zts-20100525/  

If you want to force a copy (cp) command to overwrite existing files, just do cp -X source target.

Last, but not least, we need to modify the php.ini file to load the Xdebug extension file. Open /Applications/MAMP/bin/php/php5.4.4/conf/php.ini with a text editor of your choice, go to the very bottom and uncomment the last line by removing the semicolon at the front. Don't close the file just yet.

Now relaunch MAMP, go to http://localhost/MAMP/phpinfo.php. If everything went well, you should find this within the output: xdebug-in-phpinfo

If it did not work, please make sure that you really copied over the xdebug.so and have the right path in your php.ini file.


Start Debugging

Before we can actually start debugging, we need to enable Xdebug. Therefore, I hope you didn't close out your php.ini, as we need to add this line to the very end, after the zend_extension option:

xdebug.remote_enable = On  

Save and close your php.ini file and restart MAMP. Go to http://localhost/MAMP/phpinfo.php again and search for xdebug.remote on the site. Your values should look exactly like mine: xdebug-remote-in-phpinfo

If they do not, follow the same procedure you used to add remote_enable = On for the other statements at the end of your php.ini file.

Now, open your IDE of choice. You can use Xdebug with a number of popular software solutions like Eclipse, Netbeans, PhpStorm and also Sublime Text. Like I said before, I am going to use PhpStorm EAP 6 for this demo.

Inside of PhpStorm, open the application preferences and find your way to "PHP \ Debug \ DBGp Proxy" on the left hand side, like in the screenshot below: phpstorm-debug-settings

Now choose your personal IDE key. This can be any alphanumeric string you want. I prefer to just call it PHPSTORM, but XDEBUG_IDE or myname would be perfectly fine too. It is important to set the "Port" value to 9000 as our standard Xdebug configuration uses this port to connect to the IDE.

Tip: If you need to adjust this, add xdebug.remote_port = portnumber to your php.ini file.

Attention: Other components may change this value inside of PhpStorm, so watch out for it if something fails.

Next, click that red little phone button with a tiny bug next to it on the top toolbar. It should turn green. This makes PhpStorm listen for any incoming Xdebug connections. phpstorm-bug-phone

Now we need to create something to debug. Create a new PHP file, call it whatever you'd like and paste in the following code:

<?php    // Declare data file name  $dataFile = 'data.json';    // Load our data  $data = loadData($dataFile);    // Could we load the data?  if (!$data) {      die('Could not load data');  }    if (!isset($data['hitCount'])) {      $data['hitCount'] = 1;  }  else {      $data['hitCount'] += 1;  }    $result = saveData($data, $dataFile);    echo ($result) ? 'Success' : 'Error';    function loadData($file)  {      // Does the file exist?      if (!file_exists($file)) {          // Well, just create it now          // Save an empty array encoded to JSON in it          file_put_contents($file, json_encode(array()));      }        // Get JSON data      $jsonData = file_get_contents($file);      $phpData  = json_decode($jsonData);        return ($phpData) ? $phpData : false;  }    function saveData($array, $file)  {      $jsonData = json_encode($array);      $bytes = file_put_contents($file, $jsonData);        return ($bytes != 0) ? true : false;  }  

Now this code is falsy by default, but we will fix it in a moment, in the next section.

Make sure everything is saved and open up your browser to the script we just created. I will use Google Chrome for this demo, but any browser will do.

Now let's take a moment to understand how the debugging process is initialized. Our current status is: Xdebug enabled as Zend extension, listening on port 9000 for a cookie to appear during a request. This cookie will carry an IDE key which should be the same as the one we set-up inside of our IDE. As Xdebug sees the cookie carrying the request, it will try to connect to a proxy, our IDE.

So how do we get that cookie in place? PHP's setcookie? No. Although there are multiple ways, even some to get this working without a cookie, we will use a little browser extension as a helper.

Install the "Xdebug helper"" to your Google Chrome browser or search for any extension that will do it for the browser you are using.

Once you've installed the extension, right click the little bug appearing in your address bar and go to the options. Configure the value for the IDE key to match the key you chose in your IDE, like so: xdebug-browser-extension

After configuring it, click the bug and select "Debug" from the list. The bug should turn green: xdebug-browser-extension-active

Now, go back to PhpStorm or your IDE of choice and set a "breakpoint". Breakpoints are like markers on a line which tell the debugger to halt the execution of the script at that breakpoint.

In PhpStorm, you can simply add breakpoints by clicking the space next to the line numbers on the left hand side: phpstorm-breakpoint

Just try to click where the red dot appears on the screenshot. You will then have a breakpoint set at which your script should pause.

Note: You can have multiple breakpoints in as many files as you'd like.

Now we are all set. Go back to your browser, make sure the bug is green and just reload the page to submit the cookie with the next request.

Tip: if you set a cookie, it will be available to the next request.

If everything goes according to plan, this window should pop up inside of PhpStorm to inform you of an incoming debug connection: phpstorm-incoming-debug-connection

Did the window not popup for you? Let's do some troubleshooting and repeat what needs to be set in order for this to succeed:

  1. You should find Xdebug info inside of phpinfo()'s output. If not, get the xdebug.so file in the right place and set up your php.ini file.
  2. Set PhpStorm DBGp settings to your IDE key e.g. "PHPSTORM" and port "9000″.
  3. Make PhpStorm listen for incoming debug connections using the red phone icon which will then turn green.
  4. Set a breakpoint in your code, or select "Run \ Break at first line in PHP scripts" to be independent from any breakpoints. Note that this is not suited for practical use.
  5. Get a browser extension to set the Xdebug cookie.
  6. Make sure the browser extension has the same IDE key in it that you chose inside of your IDE.
  7. Reload the page and PhpStorm should get the connection.

If you get the dialog seen on the previous image, please accept it. This will take you into debug mode, like so: phpstorm-in-debug-mode

You can see that the debugger stopped the script's execution at your breakpoint, highlighting the line in blue. PHP is now waiting and controlled by Xdebug, which is being steered by your very own hands from now on.

Our main workspace will be the lower section of the IDE which is already showing some information about the running script (the superglobals). phpstorm-debugger-vars

And would you look at that? There's the cookie we just set to start the debugging session. You can now click through the superglobals and inspect their values at this very moment. PHP is waiting, there is no time limit, at least not the default 30 seconds.

On the left side, you'll see a few buttons. For now, only "Play" and "Stop" are of interest to us. The green play button will resume the script. If there is another breakpoint in the code, the script will continue until it reaches the breakpoint and halt again.

The red stop button aborts the script. Just like PHP's exit or die would do. phpstorm-debugger-play-stop

Now the really interesting ones come in the upper section of the debug window: phpstorm-debugger-controls

Let's quickly check them out:

  1. Step Over: This means step one line ahead.
  2. Step Into: If the blue line highlights, for example, a function call, this button let's you step through the insights of the function.
  3. Step Out: If you stepped into a function and want to get out before the end is reached, just step out.
  4. Run to cursor: Let's say that, for example, your file is 100 lines long and your breakpoint was set at line two in order to inspect something. Now you want to quickly run to the point where you just clicked your cursor to – this button is for you. You can click "Step over" n times too ;)

Now don't worry, as you use Xdebug you will rapidly adapt to the shortcuts on the keyboard.


Actually Debugging Some Example Code

I already told you that the code you copy/pasted is falsy, so you'll need to debug it. Start stepping over the code, statement by statement.

Note that the blue line only halts on lines which actually contain a command. Whitespace and comments will be skipped.

Once you reach the function call to loadData, please do not step into it, just step over and halt on the if statement. phpstorm-debugger-you-cant-go-back

You can see two new variables in the "Variables" panel on the bottom of the screen. Now, why did the $data variable return false? It seems like the script should have done its job. Let's take a look. Go back to line seven to step into the function call -> bam! We get a message informing us that we can not "step back". In order to get your debugger to line seven again, you need to stop this session and reload the page in the browser. Do so and step into the function call this time.

Stop on the return statement inside of the loadData function and see what happened: phpstorm-debugger-in-a-function

The $phpData array is empty. The return statement uses a ternary operator to detect what to return. And it will return false for an empty array.

Fix the line to say:

return $phpData;  

As json_decode will either return the data or null on failure. Now stop the debug session, reload your browser, and step over the function call this time. phpstorm-debugger-still-falsy-data

Now it seems like we still have a problem as we step into the condition. Please fix the condition to use is_null() to detect what's going on:

if (is_null($data)) {      die('Could not load data');  }  

Now it's up to you to try and step around a bit. I would suggest to revert the script to the original falsy version, debug it with echo's and then compare how that feels in comparison to using Xdebug.


Conclusion

Throughout this article you should have gained a lot of new knowledge. Don't hesitate to read it again and to help a friend set up Xdebug – nothing better than that!

You may want to try replacing your usual debug behavior by using Xdebug instead. Especially with larger, object-oriented projects, as they become much easier to debug and even catch up on the flow, if you don't get something right away.

Note that this is just the tip of the iceberg. Xdebug offers much more power which needs to be explored as well.

Please feel free to ask any questions in the comments and let me know what you think.

Building Ribbit in Scala

In this tutorial we will implement the Ribbit application in Scala. We'll be covering how to install the Play web framework, a NetBeans plugin for it, and finally the code in Scala. If you are new to Scala, check out this previous tutorial which will help you set up your environment and provides you with a general platform that you can build upon.

Even though the essence of Ribbit is to create/send/read Ribbits (our version of tweets), we will spend a large part of this tutorial explaining how Play works, authentication, and persistence. After these are in place, the rest becomes much easier. We will also implement ribbit creation, submission and listing out all ribbits. Following someone, advanced user settings, and direct messages will be an extra assignment for you to complete on your own. I am sure if you manage to follow along with this tutorial and create Ribbit as explained below, these three functionalities will be easily accomplished as homework.


Download and Install Play

There are quite a few web frameworks for Scala. Some are purely functional and a few are somewhat MVC-ish. I've chosen Play for this example because it resembles an MVC architecture and it should be more familiar to people used to these kinds of frameworks. Additionally, it is one of the best and most recommended web frameworks for Scala.

So, go ahead and download Play for Scala. Please note this tutorial was written when the latest stable version was 2.1.1, you may need to adapt the content below for newer versions.

Installing Play is as simple as extracting the archive into a folder with both read and write permissions and then adding the path to the "play" executable to your PATH. At the time of writing this article, the only requirement for Play is Java 6.


Installing the Play Plugin for NetBeans

There is a very nice plugin for NetBeans which will make your life easier while working with Play. It allows you to create and manage Play projects directly from NetBeans. Go ahead and download the Play plugin for NetBeans from the official plugin page. After you have the .nbm file downloaded, just add it to NetBeans using its plugin manager.

Next, you'll need to specify the path to the "play" executable for your NetBeans plugin. Go to Tools / Options / Miscellaneous / Play. Browse to where you extracted Play's archive, until you can find the executable itself. Here's what it looked like for me: NetBeansPlayHomeSettings


Creating the Project

In NetBeans select File / New Project and choose Play / Simple Scala Application. NetBeansNewPlayScalaApplication

Then specify the folder you want your project to reside in. NetBeans will generate basic settings and a directory structure for you. NetBeansInitialPlayProject


Configuration for Building the Project

Before you can run your project, you have to make sure the correct SBT version is being used. By default version 0.11.3 is required, but I have 0.12.2 installed. You may have another version. So switch to the "Files" view in NetBeans and locate the Play project you created. If you are not using NetBeans just use your favorite file manager to find the project's folder. You will find there, in the "project" subfolder a file called "build.properties". Edit it and change the sbt.version to the correct value. If you don't have SBT installed, please review the tutorial I mentioned in the introduction to this article. It explains all the details on how to install SBT.

If you have recently updated SBT, don't forget to republish the NetBeans SBT plugin locally. Go to your "nbsbt" folder and run these commands:

rm -r ~/.ivy2/local/org.netbeans.nbsbt  sbt clean compile publish-local

This will also solve any errors telling you that SBT can't find the NetBeans plugin or that an incompatible binary type was detected.

However, Play has a little bug, and can not use the user's ~/.ivy2 repository. Instead, it uses its own local repositories. There are several workarounds that you can find on the Internet, the easiest one I've found, is to just create a symbolic link in Play's folder / repository/local that points to ~/ivy2/local/org.netbeans.nbsbt.

In the same directory, in the plugins.sbt file, make sure the proper Play version is set at this line:

// Use the Play sbt plugin for Play projects  addSbtPlugin("play" % "sbt-plugin" % "2.1.1")

Finally, in the same directory, in the file called Build.scala, make sure the application's name has no white spaces. If you specified your project with white spaces in its name, this will be wrongly set.

val appName         = "RibbitInScala"

Afterwards, you should be able to right click on the Ribbit in Scala project in the "Projects" view and successfully execute "Build". Building the project for the first time will take a little while to complete. You should see the progress in an SBT window in NetBeans. Subsequent builds should take only a few seconds.

Finally, we can run our project. Just right click on it and select "Run". In NetBeans' output window, you will see instructions on how to access your project. If all goes well, these should be the last lines in that log:

[info] Done updating.  --- (Running the application from SBT, auto-reloading is enabled) ---    [info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000    (Server started, use Ctrl+D to stop and go back to the console...)

We can now see our application running on localhost's port 9000. PlayWelcome

This is the default Play welcome screen. It is like this because we have not yet implemented any actual application code. If you see this, you are up and running and ready for the next section. Congratulations.


Basic Play Configuration

Play is very similar to other MVC web frameworks, so I won't go into great detail about its inner workings. In this section, let's just create a simple "Hello World" view and controller, which will be shown using a default route, so that we can get accustomed with Play's architecture.

In the Configuration/routes file, you can see that every call to the root (/) is redirected to the Application controller.

GET	/	controllers.Application.index

In controllers, you will find Application.scala. The code in this file will render the "index" template from views.

def index = Action {      Ok(views.html.index("Your new application is ready."))    }

In the views folder, there are a couple of files: index.scala.html and main.scala.html. The first one will call the second one to show you the content. In the second one, there is an HTML structure, CSS inclusions, JavaScript library inclusions and a few other things. Feel free to play around with these files, but explaining the content in them is however not the concern of this article.

In Application.scala change the parameter being passed into index() to "Hello World".

Ok(views.html.index("Hello World"))

Then modify index.scala.html to display it.

@(message: String)    @main("Our first content") {  	<p>@message</p>  }

The first line in a template file is the function signature. (message: String) means this view is getting a single parameter called "message" of the type String. Then comes @main, a function that returns a paragraph HTML tag with the message contained inside of it. But for all of this to work we need main.scala.html also. This has a different signature. The first parameter which is the title (check your browser's tab / title) and the other one is the content. "Our first content" will be the title and the return value of main will be the content.

@(title: String)(content: Html)

title is a String and content must be HTML. The rest of the main.scala.html file is self-explanatory. After a refresh in your browser, you will see "Hello World" instead of the previous documentation and welcome screen.

If you want to learn more about Play's inner workings check out the official documentation.


Creating the Home Page and Login Screen

As usual with these Ribbit tutorials, we will work with the following resources introduced in "The Design" article. So, go ahead and download the layout.zip file and extract it. We will refer to this folder as "LAYOUT_HOME".

Getting the Files

We need less.js in our Play project, so copy it from LAYOUT_HOME into our project's "public/javascripts" folder. Then copy style.less from LAYOUT_HOME to our project's "public/Stylesheets" folder. Continue with copying LAYOUT_HOME/gfx/frog.jpg, logo-nettuts.png and logo.png to our project's "public/images" folder.

Preparing the Views

At this point we don't care about authentication and form generation. We will just take and adapt the HTML code from LAYOUT_HOME/home.html so that we have something visual to work with.

The HTML skeleton of our Ribbit app will reside in the view called main.scala.html. You actually already have this view generated, as we've seen it in the previous section, now just modify it like so:

@(title: String)(content: Html)    <!DOCTYPE html>    <html>      <head>          <title>@title</title>          <link rel="stylesheet" media="screen" href='@routes.Assets.at("stylesheets/main.css")'>  		<link rel="stylesheet/less"  media="screen" href='@routes.Assets.at("stylesheets/style.less")'>          <link rel="shortcut icon" type="image/png" href='@routes.Assets.at("images/favicon.png")'>          <script src='@routes.Assets.at("javascripts/jquery-1.7.1.min.js")' type="text/javascript"></script>          <script src='@routes.Assets.at("javascripts/less.js")' type="text/javascript"></script>      </head>      <body>  		<header>  			<div class="wrapper">  				<img src='@routes.Assets.at("images/logo.png")'>  				<span>Twitter Clone</span>  				<form>  					<input name="email" type="text">  					<input name="password" type="password">  				</form>  			</div>  		</header>          @content  		<footer>  			<div class="wrapper">  				Ribbit - A Twitter Clone Tutorial<img src='@routes.Assets.at("images/logo-nettuts.png")'>  			</div>  		</footer>      </body>  </html>

As you can see the code now references the "style.less" file we introduced and the "less.js" JavaScript and all paths to images were also updated to use Play's '@routes.Assets.at(...)' syntax. To avoid confusing the editors with double quotes inside double quoted HTML tags, I've chosen to single quote the HTML tags that are using Play variables or methods.

The next file we need to update is our index.scala.html view. This is the index file providing the content for the main page. What we return from this will be inserted into main.scala.html at the line where "@content" is specified.

@(message: String)    @main("Ribbit in Scala & Play") {    <div id="content">  	<div class="wrapper">  		<img src='@routes.Assets.at("images/frog.jpg")'>  		<div class="panel right">  			<h1>New to Ribbit?</h1>  			<p>  			<form>  				<input name="email" type="text">  				<input name="password" type="text">  				<input name="password2" type="password">  				<input type="submit" value="Create Account">  			</form>  		</div>  	</div>  </div>    }

In this case we just changed the title that is passed to main and returned plain old HTML code.

Now, if you run your project and access http://localhost:9000 you should see an almost working home page for Ribbit. RibbitFirstAttempt

It's not yet perfect, but we have styled forms and all images are correctly referenced.

Correcting the Stylesheets

Now we have to check and update our style.less file to use the backgrounds and other things from our image directory. Of course, the first thing will be to copy the rest of the files from LAYOUT_HOME/gfx to our project's "public/images" folder.

Play with Scala, supports LESS right out of the box. To use this feature we first need to drop less.js from our views and transform our style.less stylesheet into a Play asset. Start by just deleting the following line from main.scala.html:

<script src='@routes.Assets.at("javascripts/less.js")' type="text/javascript"></script>

Now, if you refresh your project's page in the browser, it will look ugly and unstyled. RibbitUnstyled

Then move "style.less" from the project's "public/Stylesheets" folder into the "app/assets/stylesheets" folder. Create it, if needed. Rename "style.less" into "main.less". Play will automatically compile it into "public/Stylesheets/main.css" and we can delete the reference to "style.less" from main.scala.html.

Refresh your browser window again and make sure nothing is cached. You may need to stop and run your Play project again for the effects to take place. If all goes well, you should see a page similar to how it looked like initially. There may be some slight differences, but don't worry, we will fix them in a minute.

Here is how the "head" part of your main.scala.html file should look like now.

<head>  	<title>@title</title>  	<link rel="stylesheet" media="screen" href='@routes.Assets.at("stylesheets/main.css")'>  	<link rel="shortcut icon" type="image/png" href='@routes.Assets.at("images/favicon.png")'>  	<script src='@routes.Assets.at("javascripts/jquery-1.7.1.min.js")' type="text/javascript"></script>  </head>

Finally, edit "main.less" and replace all "gfx/" folder specifications for images with "/assets/images/". You may need to fix a couple widths and heights also, because the less file may be compiled differently than the JavaScript version. Afterwards, here is what we end up with: RibbitIndexStyled


User Management

Play's Built-in Authentication Functions

For our example, we will simply use Play's built-in authentication mechanisms. These are pretty good and quite complex, so we will only take what is absolutely needed for us. In Application.scala we will define a form and some actions for authentication.

package controllers    import play.api._  import play.api.mvc._  import play.api.data._  import play.api.data.Forms._    import models._  import views._    object Application extends Controller {    	val loginForm = Form(  		tuple(  			"email" -> text,  			"password" -> text  		) verifying ("Invalid email or password", result => result match {  				case (email, password) => check(email, password)  			})  	)    	def check(username: String, password: String) = {  		(username == "john.doe@gmail.com" && password == "123")  	}    	def index = Action { implicit request =>  		Ok(html.index(loginForm))  	}    	def authenticate = Action { implicit request =>  		loginForm.bindFromRequest.fold(  			formWithErrors => BadRequest(html.index(formWithErrors)),  			user => Redirect(routes.Application.public).withSession("email" -> user._1)  		)  	}    	def logout = Action {  		Redirect(routes.Application.index).withNewSession.flashing(  			"success" -> "You've been logged out"  		)  	}    	def public = Action { implicit request =>  		Ok(html.public("Logged in")("John Doe"))  	}    }

loginForm is a value we will use to authenticate our user. This form will be used in the index.scala.html view and it will call the authenticate action on our controller (we will study the view in a moment). The validation on the form will kick in and the pattern match will force a call to the "check" method. For the time being, check only returns a true or false value for the hard-coded user, john.doe@gmail.com and password 123.

The index function renders the index view with the loginForm sent in as parameter. We need this to be shown on our home page.

The authenticate function binds to the form: if there are any errors, it goes back to the index page or if it was successful, it will render a view called "public" with the session for that view, populated with the user's email. This is a very important step because if you omit the ".withSession" call, even though your user is authenticated, you will have no way of knowing which user was logged in.

Finally, logout clears up the session while the public function renders the public view, at this point with just the hard-coded user name "John Doe".

Update Routes

In the previous section we created several new actions for our controller. We now have to update our routes to accommodate these new actions:

# Routes  # This file defines all application routes (Higher priority routes first)  # ~~~~    # Home page  GET     /                           controllers.Application.index    # Authentication  POST    /login                      controllers.Application.authenticate  GET     /logout                     controllers.Application.logout    # Message  GET     /public						controllers.Application.public    # Map static resources from the /public folder to the /assets URL path  GET     /assets/*file               controllers.Assets.at(path="/public", file)

We added definitions for login, logout, public and of course for the authenticate action called from the form. This is enough for the time being.

Add the Login Form to the Header

We now have a controller and route actions, next we'll update our views. The first one to take care of is main.scala.html. We will have to update the "header" part so that it will display a form, from the controller, instead of the two built-in inputs.

<header>  	<div class="wrapper">  		<img src='@routes.Assets.at("images/logo.png")'>  		<span>Twitter Clone</span>  		@loginForm  	</div>  </header>

@loginForm has to be specified as a parameter, so the first line of the file becomes:

@(title: String)(loginForm: Html)(content: Html)

Now we will build the form's content in the index.scala.html view and pass it to main.

@(form: Form[(String,String)])(implicit flash: Flash)    @main("Welcome to Ribbit in Scala") {  	@helper.form(routes.Application.authenticate) {  		<input type="email" name="email" placeholder="Email" id="email" value='@form("email").value'>  		<input type="password" name="password" id="password" placeholder="Password">  	}  } {  <div id="content">  	<div class="wrapper">  		<img src='@routes.Assets.at("images/frog.jpg")'>  		<div class="panel right">  			<h1>New to Ribbit?</h1>  			<p>  			<form>  				<input name="email" type="text">  				<input name="password" type="text">  				<input name="password2" type="password">  				<input type="submit" value="Create Account">  			</form>  		</div>  	</div>    </div>  }

One important piece of code in this view is: @helper.form(routes.Application.authenticate). This is how we call authenticate on our Application controller from the form.

Create a Public View

Finally, create the public.scala.html view so we have a destination to redirect to in case of a successful login. This will be mostly empty at this point.

@(title: String)(user: String)    @main("Public Tweets") {  	<a id='btnLogOut' href="@routes.Application.logout" class="logout">logout</a>  } {    	<div>@user</div>    }

Getting a Slick Database Backend

Scala database backends are very cool, because they provide a syntax which hides SQL or other data languages and they map their functionality directly as Scala classes. You may think of them like ORM libraries, but implemented in a much more optimal way. Our database backend of choice is called Slick. Installing it will be as simple as adding it as a dependency in our build.scala.

"com.typesafe.slick" %% "slick" % "1.0.1",  "com.h2database" % "h2" % "1.3.166"

The first line is the Slick library, while H2 is the database that we will use. H2 is the equivalent of MySQL or Postgres or whatever your favorite database server may be. Of course, these lines go into the appDependencies definition.

val appDependencies = Seq(  	"org.mindrot" % "jbcrypt" % "0.3m",  	"com.typesafe.slick" %% "slick" % "1.0.1",  	"com.h2database" % "h2" % "1.3.166"  )

Accounts, Databases and Authentication

Managing Accounts With a Model

It's now time to make our application actually do some kind of authentication. We will introduce a model called Account. Create a file called Account.scala in your source packages / models folder. You may have to create the models folder if it's missing.

The Account model will be responsible for user management. It will connect to the database and find our John Doe user, authenticate him, and provide other useful search methods for us. Here's what our model looks like:

package models    import org.mindrot.jbcrypt.BCrypt  import scala.slick.driver.H2Driver.simple._  import Database.threadLocalSession    case class Account(id: Int, email: String, password: String, name: String)    object Account {    	object Users extends Table[(Int, String, String, String)]("USERS"){  		def id = column[Int]("ID", O.PrimaryKey)  		def email = column[String]("EMAIL")  		def password = column[String]("PASSWORD")  		def name = column[String]("NAME")    		def * = id ~ email ~ password ~ name  	}    	def authenticate(email: String, password: String): Option[Account] = {  		findByEmail(email).filter { account => BCrypt.checkpw(password, account.password) }  	}    	def findByEmail(email: String): Option[Account] = findBy("email", email)    	def findById(id: Int): Option[Account] = findBy("id", id.toString)    	def findAll(): Seq[Account] = findById(1).toSeq    	def findBy(field: String, value: String): Option[Account] = {  		val user = Database.forURL("jdbc:h2:mem:users", driver = "org.h2.Driver") withSession {  			Users.ddl.create  			Users.insert(1, "John.Doe@gmail.com", BCrypt.hashpw("123", BCrypt.gensalt()), "John Doe")  			val foundUsers = field match {  				case "email" => for {  						u <- Users if u.email.toLowerCase === value.toLowerCase  					} yield(u)  				case "id" => for {  						u <- Users if u.id === value.toInt  					} yield(u)  			}    			foundUsers.firstOption  		}    		user map {  			case (id, email, password, name) => new Account(id, email, password, name)  		}  	}    }    class NullAccount(id: Int = -1, email: String = "not@set", password: String = "", name: String = "Unknown")  extends Account(id: Int, email: String, password: String, name: String)  {  }

Well, it's pretty long, allow me to explain it line-by-line.

  • Line 1 – the package for this file has to be "models"
  • Lines 3-5 – import encryption, database driver and session libraries
  • Lines 7-8 – we define a class Account and an object for it with constructor parameters
  • Lines 11-15 – we define a User object that extends Table. This is a link between Scala and our database. In it, we have all the parameters that characterize a user.
  • Lines 20-22 – define a function called "authenticate". This will be called from the Application controller's form instead of "check". It will return an optional Account object. It may return None if the user is not found or the authentication fails. The logic in this class calls another method defined below which returns an Account for an email and then checks if the account's password matches what we typed in the form. At this point we also introduced encryption for the password.
  • Lines 24-26 – two functions for finding a user by email and by id. We may not need the findById but I've put it in here for exemplification.
  • Line 28 – will find all of the users. At this point though, it is not yet implemented, we just return a user with id 1 as a sequence.
  • Lines 30-49 – is where most of our logic is contained. findBy is a method that connects to an H2 database residing in memory. This is a temporary DB and we will just insert John Doe into it. File persistence will come a little later. Next, the findBy method finds all of the users from the DB, based on ID or email, depending on the parameter specified. Finally, it returns an Option[Account].
  • Lines 53-55 – we define a null version of Account. Just in case we end up on the public page with an unknown, but authenticated user, we don't want our view to break.

Connecting the Application Controller to Accounts

Now that Account can authenticate our user, we can get rid of the "check" function in the Application controller and change our form into this:

val loginForm = Form(  	tuple(  		"email" -> text,  		"password" -> text  	) verifying ("Invalid email or password", result => result match {  			case (email, password) => Account.authenticate(email, password).isDefined  		})  )

Instead of calling check we will call Account.authenticate and check if the returned value is defined, as in the case of a failure, it can return None.

def public = Action { implicit request =>  	def getLoggedInEmail = request.session.get("email") match {  		case Some(email) => email  		case None => ""  	}  	def getUserFromOption(user: Option[Account]) = user match {  		case Some(account) => account  		case None => new NullAccount  	}  	val user = getUserFromOption(Account.findByEmail(getLoggedInEmail))  	Ok(html.public("Logged in")(user))  }

The public function has to be updated as well to get a user account by the email address, kept in the session.

Update the View

The public.scala.html view has to be updated in order to get a parameter of type Account and be able to obtain all user information from it.

@(title: String)(user: Account)    @main("Public Tweets") {  	<a id='btnLogOut' href="@routes.Application.logout" class="logout">logout</a>  } {    	<div>@user.name</div>    }

Here, we just output user's name at this point. AuthJohnDoe


Creating Users and Using Real Persistence for Them

Now that we have authentication with our database working, it's time to make the database persistent. It is also a good time to implement user creation. We will again be forced to rethink parts of our actual design. In previous sections we started our reasoning and development with the business logic (the code in Applications.scala and in Account.scala) and worked our way up to the views. I propose we take a reverse approach this time, so that you can see an example where we start with index.scala.html, our view, and develop step by step toward the functionality that we want, ending with Account.scala.

Writing a Play Form for Account Creation

We have to modify index.scala.html so that our second form, for the user creation, will also be created using Play's helpers, so that this code:

<p>  <form>  	<input name="email" type="text">  	<input name="password" type="text">  	<input name="password2" type="password">  	<input type="submit" value="Create Account">  </form>

Becomes this, instead:

@helper.form(routes.Application.createAccount) {  	<input type="text" name="name" placeholder="Full Name" id="name" value='@createForm("name").value'>  	<input type="email" name="email" placeholder="Email" id="email" value='@createForm("email").value'>  	<input type="password" name="password" id="password" placeholder="Password">  	<input type="password" name="confirm" id="password2" placeholder="Confirm Password">  	<input type="submit" value="Create Account">  }

In this code, there are two essential pieces:

  1. @createForm("...").value – which is a form that we will send in from the controller. This also requires us to change the signature of our view (see below).
  2. routes.Application.createAccount – which is the action that we will create in our controller. This requires us to update our routes and of course the Application controller.

The view's signature becomes:

@(loginForm: Form[(String,String)], createForm: Form[(String, String, String, String)])(implicit flash: Flash)

As you can see, we are now always getting two forms. To better differentiate them, we also updated the name of the previous variable to "loginForm", so we have to update the input for login as well.

<input type="email" name="email" placeholder="Email" id="email" value='@loginForm("email").value'>

We also had to update main.less to accommodate the extra input, but these small marginal adjustments here-and-there are not that relevant. RibbitLoginWithNewCreateForm

Adding the New Route

This is easy, just one more line in the "routes" file.

# User Creation  POST /create						controllers.Application.createAccount

Adding in New Controller Functionality

First, add a new form for creating a user:

val createForm = Form(  	tuple(  		"name" -> text,  		"email" -> text,  		"password" -> text,  		"confirm" -> text  	) verifying ("Invalid email or password", result => result match {  			case (name, email, password, confirm) => Account.create(name, email, password, confirm).isDefined  		})  )

This is where we define the four fields that we'll need. Then in the case where we call Account.create(...).isDefined, this will force us to write a "create" function in our Account model.

Next, we need to define the "createAccount" action:

def createAccount = Action { implicit request =>  	createForm.bindFromRequest.fold(  		formWithErrors => BadRequest(html.index(loginForm,formWithErrors)),  		user => Redirect(routes.Application.public).withSession("email" -> user._2)  	)  }

For this action, on failure, we will redirect to the index page and send in the loginForm plus our formWithErrors. This will help keep the user's filled in form data present, after a form submission. On success, we will just go to the "public" page, as we do when the authentication succeeds. We will also set and pass the email through the session.

Finally, we need to adjust all the other calls to the index view to take both forms as parameters:

def index = Action { implicit request =>  	Ok(html.index(loginForm, createForm))  }    def authenticate = Action { implicit request =>  	loginForm.bindFromRequest.fold(  		formWithErrors => BadRequest(html.index(formWithErrors, createForm)),  		user => Redirect(routes.Application.public).withSession("email" -> user._1)  	)  }

Creating the Account in the Database

Up until now, all of our code for user creation was just to support the framework: views, routes, controller actions, forms. Now it's time for some serious business. We will need to change Account.scala quite a bit, so below is the code for the changed version and then afterwards, the explanation.

package models    import org.mindrot.jbcrypt.BCrypt  import scala.slick.driver.H2Driver.simple._  import Database.threadLocalSession    case class Account(email: String, password: String, name: String)    object Account {    	object User extends Table[(String, String, String)]("USERS"){  		def email = column[String]("EMAIL", O.PrimaryKey)  		def password = column[String]("PASSWORD")  		def name = column[String]("NAME")    		def * = email ~ password ~ name  	}    	def authenticate(email: String, password: String): Option[Account] = {  		findByEmail(email).filter { account => BCrypt.checkpw(password, account.password) }  	}    	def create(name: String, email: String, password: String, confirm: String): Option[Account] = {  		if (password != confirm) None  		else {  			Database.forURL("jdbc:h2:users", driver = "org.h2.Driver") withSession {  				try {  					User.ddl.create  				} catch {  					case e: org.h2.jdbc.JdbcSQLException => println("Skipping table createion. It already exists.")  				}  				User.insert(email, BCrypt.hashpw(password, BCrypt.gensalt()), name)  			}  			findByEmail(email)  		}  	}    	def findByEmail(email: String): Option[Account] = findBy("email", email)    	def findByName(name: String): Option[Account] = findBy("name", name)    	def findAll(): Seq[Account] = findByName("John Doe").toSeq    	def findBy(field: String, value: String): Option[Account] = {  		val user = Database.forURL("jdbc:h2:users", driver = "org.h2.Driver") withSession {  			val foundUser = field match {  				case "email" => for {  						u <- User if u.email.toLowerCase === value.toLowerCase  					} yield(u)  				case "name" => for {  						u <- User if u.name.toLowerCase === value.toLowerCase  					} yield(u)  			}    			foundUser.firstOption  		}    		user map {  			case (email, password, name) => new Account(email, password, name)  		}  	}    }    class NullAccount(email: String = "not@set", password: String = "", name: String = "Unknown")  extends Account(email: String, password: String, name: String)  {  }

Here's what we've done:

  • We dropped the "id" for the user, as the email address is just as good as an id and we can use it for the unique key. This also led to changes in the Account's signature, in NullAccount, and in the User's signature. Users was renamed to User and now has only three fields: email, password, and name.
  • Because we removed the "id", we also changed the function "findBy". Now it can search by name and email and not by id.
  • To implement real persistence, we dropped the "mem" specification from the database connection. This makes "USERS" a real table residing in a database file called "users".
  • Finally, we added a create method to add the new user to the database. In its logic, it tries to create the table and in case it already exists, it catches the exception and just writes a nice message to the console. Check your NetBeans' Output console, the one that opens when you select "Run" on the project. The rest of the code should be fairly obvious, insert the new user into the database and then look it up and return it with the already existing function "findByEmail".

We are done. You can now create users. Have fun with them!


Post a Ribbit

Now that we are more familiar with Play, Slick and Scala, the rest of the program is quite easy to build. We will, however, implement both posting ribbits and showing all ribbits. This is also the final state of the attached source code, so I will only mention the most interesting parts here.

To create Ribbits we have to modify our public view. As a first step, you can take the code from the layout ribbit tutorial we used at the beginning and start changing it where needed. First, we need a form generated by Play instead of the hardcoded one.

<div class="panel right">  	<h1>Create a Ribbit</h1>  	<p>  		@helper.form(routes.Ribbits.createRibbit) {  		<textarea type="text" name="ribbit" placeholder="Your Ribbit here..." id="ribbit" class="ribbitText" value='@createForm("name").value' ></textarea>  		<input type="submit" value="Ribbit!">  		}    	</p>  </div>

Don't forget to update the view's signature as well.

Then we create a new controller, called Ribbits. We can now move the "public" function here, update our Application controller and our views to call Ribbits.public instead of Application.public. We then add a "createRibbit" function in the new controller, together with our form.

package controllers    [...] // many omitted imports    object Ribbits extends Controller {    	def createForm (session: Session) = Form(  		single("ribbit" -> text) verifying ("Could not add Ribbit. Sorry.", result => result match {  				case (ribbit) => RibbitRepository.create(ribbit, session.get("email"))._1.equals(ribbit)  			})  	)    	def getLoggedInUser(session: Session): Account = {  		def getLoggedInEmail = session.get("email") match {  			case Some(email) => email  			case None => ""  		}  		def getUserFromOption(user: Option[Account]): Account = user match {  			case Some(account) => account  			case None => new NullAccount  		}  		getUserFromOption(Account.findByEmail(getLoggedInEmail))  	}    	def public = Action { implicit request =>  		val user = getLoggedInUser(request.session)  		Ok(html.public("Logged in")(user)(createForm(request.session))(RibbitRepository.findAll))  	}    	def createRibbit = Action { implicit request =>  		createForm(request.session).bindFromRequest.fold(  			formWithErrors => BadRequest(html.public("Logged in")(getLoggedInUser(request.session))(formWithErrors)(RibbitRepository.findAll)),  			ribbit => Redirect(routes.Ribbits.public)  		)  	}  }

Then we create a new model, RibbitRepository. It will be responsible for creating and listing out all ribbits.

def create(content: String, sender: Option[String]): (String,String,String,String) = {  	Database.forURL("jdbc:h2:ribbits", driver = "org.h2.Driver") withSession {  		try {  			Ribbit.ddl.create  		} catch {  			case e: org.h2.jdbc.JdbcSQLException => println("Skipping table createion. It already exists.")  		}    		def senderEmail = sender match {  			case Some(email) => email  			case None => "Unknown@email.address"  		}    		Ribbit.insert(content, senderEmail, new SimpleDateFormat("yyyy-MM-dd HH:mm").format(Calendar.getInstance.getTime))  	}  	findAll().last  }

We also modified our database, I just called it "ribbits" and both the "Ribbits" and the "Users" are in this database. A ribbit will have some content, a sender's email and a timestamp.


View All Ribbits

Finally, we updated our view to loop over all ribbits provided by the findAll function of the RibbitRepository model.

def findAll(): Seq[(String,String,String,String)] = {  	val allRibbits = Database.forURL("jdbc:h2:ribbits", driver = "org.h2.Driver") withSession {  		try {  			Ribbit.ddl.create  		} catch {  			case e: org.h2.jdbc.JdbcSQLException => println("Skipping table createion. It already exists.")  		}    		val foundRibbits = for {  			r <- Ribbit  			u <- User if u.email.toLowerCase === r.sender.toLowerCase  		} yield((r.content, r.sender, r.dateTime, u.name))  		foundRibbits.list  	}  	allRibbits  }

This same method is also called on ribbit creation, so that the list is refreshed after a submission. The view simply does a map on the sequence and outputs the content.

<div id="ribbits" class="panel left">  	<h1>Public Ribbits</h1>    	@ribbits.map { ribbit =>    	<div class="ribbitWrapper">  		<img class="avatar" src='@routes.Assets.at("images/user1.png")'>  		<span class="name">@ribbit._4</span> @ribbit._2 <span class="time">@ribbit._3</span>  		<p>  			@ribbit._1  		</p>  	</div>    	}    </div>

And here's what the final version of the signature for the view should look like:

@(title: String)(user: Account)(createForm: Form[String])(ribbits: Seq[(String,String,String,String)])  

Notice that we did not use "user" in the view, but we could have, so I decided to leave it in there just in case you wish to modify this code and use it however you please.

And here is the finished app in action. RibbitFinished


Final Thoughts

So I think now is a good time to end this tutorial. Creating additional pages for the app would be very similar to the ones we have already done here, so I'll leave this as an exercise for you. I hope I helped you to understand the basics of Scala, Play and Slick. Consider this tutorial a very basic introduction, without all of the fancy stuff like Ajax requests or auto incrementing on H2 key columns. I am sure that if you were able to follow along with this tutorial, it will provide you with a solid base that you can build on top of. Also, don't forget to check out all of the extra information and documentation about Slick, Play and Scala that I linked to throughout this tutorial.

Thank you for reading.