[Lucas Galego] JavaScript Object Oriented Programming

January 13th, 2015

When I started to work as a developer, I remember that my fellow programmers used to hate JavaScript.
I myself was not a real fan of this incredible language.
That’s why I decided to study it more deeply.
During my studies, one thing came clear to me:

JavaScript is one of the most powerfull languages I ever seen.

But… There is always a but.

Its API is terrible.

But since JavaScript is a language ready to be extended, we solve this problem using some great tools like jQuery or Undescore.js, that make the JavaScript API be really beautiful.

JavaScript is a really powerfull language, so, we can program in JavaScript using a lot of paradigms.

Let’s talk about how to implement your JavaScript code using Object Oriented Programming.

JavaScript and OOP

To understand how to make OOP code using JavaScript, we first need to understand how the variable this works.

console.log(this);

If you run this code, the console will log to you an instance of the DOM Window object representing the window of your browser (this will change if you are running this on a Node.js server).

That means that in the global scope this is the Window object.

Okay, so what if we run this code:

function some(){

console.log(this);

}

some();

If you run, you will see that again Window is logged.

That means that the this of a function is the same this from the scope where the function is defined.

So, how can I create an object and make its this referencing it?

Creating a JavaScript Object

var myObj = {

some: function(){console.log(this);}

};

myObj.some();

Now we are getting somewhere, When you run this code, it’s an Object that is logged, not a Window Object, just an Object.

If you inspect the logged object, you will se that it has a property called some. This property is a function, the function that we called.

Once we have an object, we can add properties to it:

myObj.coolProperty = “JavaScript rocks”;

And also retrieve these properties:

console.log(myObj.coolProperty)

console.log(myObj[‘coolProperty’]

Note that the properties are like keys of a map. You can retrieve them using the [] syntax, so, you can pass the properties as parameters.

var myObj = {

func1: function(){console.log(“Called 1″)},

func2: function(){console.log(“Called 2″)}

}

myObj[“func2″]();

This will prompt “Called 2″.

Creating constructors

There is another way to create an object:

function MyObject(){

this.some = function(){console.log(this);};

}

myObj = new MyObject();

console.log(myObj.some());

We just created a constructor. If you run this code, you will se now MyObject at the console.

Since we created this object using the function new, this was redefined from Window to MyObject.

Thats why when we make this.some = function(){console.log(this);}; inside the function MyObject the function is defined inside our MyObject instance.

So what happens if we run this code:

function MyObject(){

this.some = function(){console.log(this);};

}

myObj = MyObject();

console.log(myObj);

some();

Now, we don’t used new when we invoked MyObject function. That means that inside the function this remains to be Window.

Wich means

console.log(myObj);

log undefined. We don’t return anything from MyObject function, so myObj is undefined.

And that’s why we can invoke some at the global scope and it log Window.

So its very important to remember that you have to use new when you are creating an Object  from a Constructor.

Creating Public Methods

All right, now we know how to create objects and even how to create this objects from constructors.

But how can we add methods to a Object definition.

Let’s see two ways.

  • Using properties:

function MyObject(){

this.method = function(){console.log(“I’m a public method”);};
}

new MyObject().method();

or

var myObject = {

method: function(){console.log(“I’m a public method”);}

}

myObject.method();

In both examples we defined a property in an object that is a function. So we can use this function like a method.

  • Using prototype

function MyObject(){};

MyObject.prototype.method = function(){console.log(“I’m a public method”);};

new MyObject().method();

We just created a construtor for MyObject, after that, we defined in the prototype of our constructor an attribute that is a function.

Every attribute defined in the prototype of an object, is automatically, accessible by the instances of that object.

Using Inheritance

We can use prototype to define Inheritance.

function Animal(){};

Animal.prototype.eat = function(){console.log(“eating…”);};

function Dog(){};

Dog.prototype = Animal.prototype;

new Dog().eat();

Setting the prototype of the Constructor of a Dog as the prototype of Animal makes that our Dogs to have the method eat.

Defining private members

Well, you may also want to create properties and methods that are not public. This is really easy.

Every variable in JavaScript has function scope

function a(){

var b = 1;

console.log(b);

}

a();

console.log(b);

This code will log 1 and then will log undefined. That’s why when we use the word var we are saying that the variable b exists only inside the function a.

Since our objects are functions, we can use the same idea:

function MyObject(){

var privateMethod = function(){console.log(“I’m private”);};

this.publicMethod = function(){console.log(privateMethod());};

}

new MyObject().publicMethod();

console.log(new MyObject().privateMethod).

This code will log I’m private and them undefined. And thats was what we expect.

First we call the public method. It has access to our private method inside the Object instance so it con log our message.

But, outside the constructor function, the variable privateMethod dos not exists, so our code log undefined.

Conclusion

You can have a lot of fun with JavaScript. So enjoy and play a lot :)

I just introduced the concept of OOP here, there is a lot to talk about this.

You can see some great JavaScript samples here.

That’s all. See you!

[Lucas Galego] Hello world!

January 13th, 2015

Hello guys.

This is a new and refreshing blog.

I’m going to try to post here my thoughts about one of my greatest passions. That is programming.

Lets see what you will think about it.

See ya!

[Lucas Galego] Ruboto, this android works?

January 13th, 2015

I was wondering about play a little with a project called Ruboto by some time.

For who doesn’t heard anything about this project, Ruboto is a intended to make possible to write android applications with Ruby.

Since I love my old but gold Motorola Milestone and I also love Ruby this sounds really fun.

Here is what I have done:

My intention was to make a really simple application just to see the maturity of the project.

What can be more simple than a planning poker app? Well I don’t know. So I decided to make that one.

Begining from scratch:

  • You can find more about the Ruboto project at its web page.
  • You can write fully funcional apps only writing code in Ruby and using generators to make the Java wrappers.
  • You can make hybrid projects using Java and Ruby.
  • It cover almost all android API.

But… There is always a but:

  • To run Ruboto apps  you have to install the ruboto-core app to your android device.
  • If you want that your app support JIT (and who doesn’t want that?) your apk file will get bigger.

Let’s Play

To start to play you have to setup your enviroment.

You gonna need the JDK installed in your system.

Once you it installed, install the JRuby.

I recommend you to use the JRuby 1.6.4. It will also be smart, install it using rvm and create a gemset to full around.

Another dependency is the Android SDK. You can get it here.

Read the REAME file since you have downloaded it. ;)

Don’t forget to install the android sdk and the development tools.

Okay. That’s all. Now we can start the party.  :)

First we need to create an emulated device to use during our development.

To create this run the command:

android -s create avd -f -n Android_2.3 -t android-10 –sdcard 64M

To startup the emulator you created:

emulator -avd Android_2.3

Generating the Ruboto project

ruboto gen app –package better.code.planning.poker –target android-10

Just this. The Ruboto project contains code generators like Ruby on Rails.

You have now:

  • All the project structure of an Android project,
  • All the Java wrappers to your Ruby script,
  • A Hello World Ruby Script,
  • Some usefull rake tasks.

The rake tasks are:

  • rake -> Build the apk.
  • rake install start -> Build the apk, install and start it on your emulator.
  • rake install:clean start -> Also clean the previous build from your emulator.
  • rake update_scripts:restart -> Updates only the ruby script on your device, it can save you some compilation time.

You can also make the deploy to the device by yourself using the comand:

adb install ruboto-core.apk

Let’s start to code

First lets define a better title to our activity:

Edit the application name into the file: res/values/strings.xml

<string name="app_name">Planning Poker!</string>

Now we can finally see one of the good points of using Ruboto.

When developing Android apps, you have to deal with a lot of xml files that handle how the templates will be defined.

With Ruboto, we can define our template using its much more delicious DSL.

Edit the file: src/poker_activity.rb

require 'ruboto'

java_import 'android.content.Intent'

ruboto_import_widgets :Button, :LinearLayout, :TableLayout, :TableRow

$activity.handle_create do |bundle|
  setTitle 'Lets make this Sprint!'

  setup_content do
    table_layout do
        table_row do
          button :text => ' 1 ', :text_size => 57
          button :text => ' 2 ', :text_size => 57
          button :text => ' 3 ', :text_size => 57
        end
        table_row do
          button :text => ' 5 ', :text_size => 57
          button :text => ' 8 ', :text_size => 57
          button :text => ' 13', :text_size => 57
        end
        table_row do
          button :text => ' 20', :text_size => 57
          button :text => ' 40', :text_size => 57
          button :text => '100', :text_size => 57
        end
        table_row do
          button :text => 'Zzz', :text_size => 57
          button :text => ' 0 ', :text_size => 57
          button :text => ' ? ', :text_size => 57
        end
    end
  end
end

We defined our layout using the Ruboto DSL with the methods setup_content, table_layout and table_row.

We set the content of each row with the method button.

Events and new Activities

Now let’s make the magic. When the user press the number he wants to vote, we will popup a new Activity with the value.

For this we need to create a new Activity.

ruboto gen class Activity –name Card

And edit the code in src/card.rb like this:

require 'ruboto'

ruboto_import_widgets :Button, :LinearLayout, :TextView

$activity.handle_create do |bundle|
  setTitle 'My vote is'

  setup_content do
    linear_layout :orientation => LinearLayout::VERTICAL do
      @text_view = text_view :text => $activity.getIntent.getExtras
                   .get("better.code.ruboto.planning.poker.vote"),
                   :text_size => 150
    end
  end

end

Now, what we need is register the event, so we can dispatch the new Activity.

First we need to register the new activity in the AndroidManifest.xml file

<activity android:name='Card' android:label='Card'>
        <intent-filter>
            <action android:name='android.intent.action.CARD'/>
            <category android:name='android.intent.category.DEFAULT'/>
        </intent-filter>
</activity>

Now, we add the handler of the action into the src/poker_activity.rb file. Just after the setup_content method:

handle_click do |view|
    i = Intent.new("android.intent.action.CARD")
    i.putExtra("better.code.ruboto.planning.poker.vote", view.text)
    startActivity(i)
end

Using the Intent instance, we can call the putExtra method. That’s the way we can pass args to our new Activity.

In the Card Activity, the args are rescued using the getExtras method.

That’s it. I hope you enjoy it just like me :)

See ya!

[Flávio Ribeiro] Disserting on Clappr: An extensible media player for the web

November 25th, 2014

Motivated by Leandro, today I’m gonna write a bit about Clappr, an open source media player for the web. If you’re Brazilian or know portuguese, there’s also some useful information at Thiago’s talk. Actually, I will inadvertently and explicitly steal some data from it.

History

During the last 4 years at Globo.com there was no team focused specifically on the development of the video player. It was a monolitic flash component based on OSMF, mainly designed for playing progressive download videos on on-demand scenarios and also cover live streams through RTMP protocol.

Globo Player 2.0
Previous Globo.com player

At the beginning things were good, but in the course of time, a lot of new features were added (like support for subtitles, advertisement, DRM, new streaming protocols, picture-in-picture, etc). Since there wasn’t an official owner of the project and maintenance programming is a dirty work, we were building a wall with crooked bricks. Player tasks started to be faced with revulsion and pain.

As the FIFA World Cup 2014 project came with a bunch of new requirements and knowing that our live video streaming stack was rebuilt (HLS in favor of RTMP), we decided to go against Joel and bootstrap a brand new video player in order to support the requirements and improve the overall performance on serving the matches and upcoming transmissions.

Open Source

At Globo.com we use hundreds of open source projects and when starting a project from scratch, we usually ask ourselves Why not open source it?. First, there’s the motto of give something back to the community, but I personally believe that committing and pushing on Github, put your code available to the world and maybe build a community around your baby acts like a fuel for your brain, pushes you to the limits of productivity.

Open source software acts like a fuel for your brain, pushes you to the limits of productivity.

Since we are in times where video delivery is very heterogeneous between browsers and devices, we choose for a plug-ins based architecture, allowing us to provide almost everything as open source, except the components that interact with our internal infrastructure.

Visit Globo.com Open Source to see more open source projects maintained by my co-workers.

Clappr Architecture

Clappr Architecture, First Meeting
Designing Clappr, you can see the full image here.

With CBSE in mind we could figure out that there were three different plug-in types:

  • Playback Plugins: Responsible for playing a given source. When embedded, Clappr will search through playback plugins until find one who canPlay() the source.

  • Container Plugins: Every playback is associated with a container. In most cases, only one container and a playback will be instantiated. It is inside containers that, guess what, the container plugins work. Some examples are the built-in stats plugin that listen for playback events (buffering, bufferfull, play/pause, etc), the spinner and the watermark.

  • Core Plugins: These are the ones who control everything. Let’s say you want two videos playing at the same time, the main one and one smaller at the corner, like a picture-in-picture. A core plugin is able to instantiate two containers with a playback plugin each, set the size of the secondary video and put it on a bigger z-index.

There’s also a bunch of built-in components, like the Mediator who is responsible for routing events between scopes (and even make the Flash ↔ JS bridge when necessary) and the Loader who manage to load all built-in and external plugins. Wat? External plugins?

External Plug-ins

It’s not only possible but simple to create your own external plug-in. There’s a Clappr Plug-ins Generator that will ask you the kind of plug-in you want to create and build the structure for you. I’ve used it to create BemTV plugins, the playback and a container plugin to show peer-to-peer statistics. Globo.com has some proprietary plug-ins such as media control bar, thumb-on-seek and others.

Clappr with Globo.com Plugins
Clappr with some Globo.com proprietary plugins used at World Cup

Technology

Current Status

Clappr already supports the mainstream formats and has some special features like DVR (travel in time on live streams). We’re heading to 1.0.0 release, but first we need to create a decent documentation and landing page. Both are on the go.

We tought that the architecture was so solid that motivated us to bootstrap mobile versions of Clappr. We already created iOS and Android repositories in case you want to follow our future progress.

Contributing

We are just three commiters, but there are some easy issues opened. If you felt encouraged in contributing, I’ll be more than glad to help you. You can find us at clappr discussion list and I’m always online as flavioribeiro at freenode.

[Rafael Biriba] User Agent do Internet Explorer 11 muda e quebra um monte de projetos

September 10th, 2014

internet-explorer-stopped-working
Fala galerinha…. Estou sumido a muito tempo aqui do blog… Vou tentar voltar a postar coisas… Serão posts curtos e objetivos, então qualquer dúvida pode me procurar nos comentários… (Preciso arrumar um tempo pra limpar esse layout horroso) :p :p

Hoje, após algumas reclamações de usuários, descobri que o IE 11 mudou seu user agent, e isso quebra vários javascripts.

Verifique o seu projeto e veja se não foi impactado.

Antes um user agent, por exemplo do IE 10 vinha assim:
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)

Então no seu javascript, para verificar se o navegador era IE, você pega o user agent e procura pela string MSIE. Provavelmente era um código assim:
this.navigator.userAgent().match(/MSIE\s([\d]+)/);

Com o novo e belíssimo IE 11, além de bonito e rápido, ele não podia perder a reputação e continuar uma droga… O user agent mudou para:
Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko

Com isso seu belíssimo javascript retorna que você não está no IE e sua aplicação se comporta de forma completamente diferente.

Para resolver isso, após muita muita pesquisa, forums, stack overflows, confesso que vi soluções que davam vontade de chorar… Então resolvi juntar um pedacinho de cada, e cheguei na seguinte solução:

1
2
3
4
5
6
7
8
9
10
function isIE() {
 return (
  (this.navigator.appName() == 'Microsoft Internet Explorer') ||
  this.navigator.userAgent().match(/MSIE\s([\d]+)/) ||
  (
   (this.navigator.appName() == 'Netscape') &&
   (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(this.navigator.userAgent()) != null)
  )
 );
}

Assim eu consigo fazer 3 verificações antes de dizer que não é IE. Se o navegador se chama “Internet Explorer”, se ele tem uma versão válida de MSIE ou se ele é um Netscape com alguma versão de Trident.

Já estou rodando esse código em produção e o problema foi solucionado. Espero que sirva para mais alguém…

Share

[Flávio Ribeiro] BemTV: Hybrid CDN/P2P Architecture for HLS Broadcasts

August 7th, 2014

During the last three years I’ve been working on the Live Video infrastructure at Globo.com and I’ve realized that one of the biggest problems we had here in Brazil is related to CDN throughput and telecom infrastructure in general. Looking at what has been happening with online streaming of live events around the world (as The Oscars and True Detective Finale) and the fights involving OTT services and telecom carriers, one can realize that this is a common problem everywhere.

With that in mind, I decided to explore this problem and as I’m attending the last year of my Master’s and my colleagues at work were bootstraping a new team to develop a video player from scratch, it happened to be the perfect timing. I joined this new team and defined my Master’s thesis theme aiming to develop a Hybrid CDN/P2P architecture for online live broadcasts using the popular HLS protocol together with WebRTC.

First, we baptized the new player as Clappr - the name “clapper” comes from clapperboard - and open-sourced the project. You can follow our progress on github and yes, we’re aware that we’ll need to write some documentation on how to deploy the player and write plugins, it is already on our backlog. A nice logo and better UI are also on the go.

After that, I’ve created a clappr plugin that tries to drain video segments from peers in order to decrease the number of requests to CDN servers, reducing the cost of transmission and enhancing system’s scalability. If something goes wrong between the peers, it will get from the CDN without impacting user experience. This project is called BemTV and today I’m releasing its first version.

BemTV in action

BemTV is open source. I must warn you that this is a nightly build and needs some improvements before debut on production environment (I’ve performed just some controlled tests) but I’m inviting you to test it on http://bem.tv and also look at the code. The video in there is in loop, emulating a live video streaming behavior.

I’ll be more than happy to answer questions and fix bugs or problems that arise. Call friends near you, look at the statistics box and tell me if the video segments are being exchanged between you guys!

[Alexandre Martins] Continuous Delivery: Deployment Smoke Tests

June 5th, 2014

I’ve always been a huge fan and advocate of using tests for developing applications. For me, working on a software without a decent suite of test is like walking on eggshells, each modification brings out the risk of breaking something on the system. To mitigate this risk I always make sure I have a minimum set of unit, integration and acceptance tests covering my application.

But does all that gives us the confidence that the system will work perfectly when it’s deployed to any of the environments, on its way through the release pipeline? I thought so until work with this guy and read this book. Tom Czarniecki firstly introduced me the concept os smoke tests, then reading Jez Humble and David Farley’s Continuous Delivery I could grok the real values of using it in conjunction with a build pipeline.

What are smoke tests?

As aforementioned, deployment smoke tests are quite handy because they give you the confidence that your application is actually running after being deployed. It uses automated scripts to launch the application and check that the main pages are coming up with the expected contents, and also check that any services your application depends on— like database, message bus, third-party systems, etc —are up and running. Alternatively you can reuse some acceptance or integration tests as smoke ones, given that they are testing critical parts of the system. The name smoke test is because it checks each of the components in isolation, and see if it emits smoke, as did with electronic circuits.

Provide clear failure diagnostics

If something goes wrong, then your smoke tests should give you some basic diagnostics explaining the reasons why your application is not working properly. In our current project at Globo.com, we are progressing towards start using Cucumber to write our smoke tests, thus having a set of meaningful and executable scripts, like this one below.

Feature: database configure
  System should connect to the database
  Scenario: should connect to the database
    When I connect to "my_app" database as root
    Then it should contain tables "users, products"

For those who like using Nagios for monitoring infrastructure, Lindsay Holmwood wrote a program called cucumber-nagios which allows you to write Cucumber tests that output the format expected of Nagios plugins, so that you can write BDD-style tests in cucumber and monitor the results in Nagios.

Knowing quickly whether you are ready or not!

Clearly rapid feedback and safety are the two major benefits of introducing smoke tests as part of a release process.

Rapid feedback

In our project, we implemented a deployment pipeline, so each new commit into the source repository is a potential deployable version to any environment, even to production. So we have the commit-stage where we run all the quick tests, and as soon as all of them passes, the acceptance-test-stage is automatically triggered, and the longer tests— integration and acceptance —are run, and once they’ve also passed, the application is automatically deployed into the dev environment. Getting a green at this stage means that it’s successfully deployed and smoke tested. But there still some exploratory testing to be performed before releasing this version into the staging environment. And in our team, this is done by the product owner, together with a developer. So as soon as they are ready to sign the story off, all they have to do is click the manual button which in turn deploy the application into the qa1 (UAT) environment, and if it’s green they can proceed, otherwise they pull the cord because something is malfunctioning, as you can see on the picture.

Don’t let the application deceive you

It’s quite frustrating, when all you need is the system to work as expected, because you are about to showcase it to your customers, and the first thing you click, all you see is a big and ugly error screen, instead of the page they were expecting. And later on you find out that it was due to database breakdown. What an embarrassing situation that could have been avoided by simply checking the smoke test diagnostics before showcasing.

[Renan Oliveira] Ontologias e sua utilização em aplicações semânticas – UFF – CASI – 2014

May 20th, 2014

Ontologias e sua utilização em aplicações semânticas – UFF – CASI – 2014 from Renan Oliveira

[Francisco Souza] Speaking at OSCON 2014

April 12th, 2014

Wow, one year without any posts! But I’m trying to get back…

This is a very short post, just to tell everybody that this year, I will have the opportunity to speak at OSCON 2014. I’m speaking about tsuru, and check more details of the talk in the tsuru blog.

[Francisco Souza] Speaking at OSCON 2014

April 12th, 2014

Wow, one year without any posts! But I’m trying to get back…

This is a very short post, just to tell everybody that this year, I will have the opportunity to speak at OSCON 2014. I’m speaking about tsuru, and check more details of the talk in the tsuru blog.