Robolectric 3.0 and shadows

Some time ago (end of 2015), I created an open source project called RxGoogleAuthentication that aims to easily get an authentication token for the Google Apis, based on OAuth2 protocol.

As all of my open source project, I never ship a code without a certain quality, and that includes proper unit testing. Shipping a project without at least that, is a lack of responsibility I think. From my point of view, a developper should be responsible of producing good code quality, or at least trying to do so. Moreover, your code could now be integrated by others on their own projects, so this is all the more important that some quality is there.

Shadows ?

To do my Unit Testing, as most of android developers, I use the Robolectric framework. I won’t get into the benefit of this framework, so you can have a look at their landing pages, but the absolute crucial one for me is that it runs on the jvm, outside the emulator. The downside of that is that you don’t have the entire Android environment which you can’t use, which is problematic in some cases.

Indeed, your tests can require to rely upon the behavior of Android components that are not available as the Android OS is not there.

To compensate that, Robolectric gave you the ability to extend the behavior of Android classes and expose them into the testing environment. These extensions of classes are called « Shadows » .

As you can read on the documentation« When an Android class is instantiated, Robolectric looks for a corresponding shadow class, and if it finds one it creates a shadow object to associate with it. Every time a method is invoked on an Android class, Robolectric ensures that the shadow class’ corresponding method is invoked first (if there is one) »

This is really powerful in a way that you can control the behavior of a Shadow Class and also add missing Shadows.

Concrete use case 

The open source project introduced at the beginning of this article is using the GoogleAuthUtil class, and more specifically the getToken() methods.

At the time I did that shadow, Robolectric didn’t have it. But it seems to have added it 5 days ago, before writing this article.

Anyway, let’s get into the entire process of creating this shadow in concrete and practical term so this would be a great learning case.

#1 Create the shadow class

To create our shadow, the convention is to prefix « Shadow » term to our class name, in our case our shadow would be ShadowGoogleAuthUtil.

The shadow class  should be annotated with the @Implements annotation whereas the methods should be annotated with the @Implementation annotation.

In our precise case, the getToken() methods of our shadow class will return a simple token string, without caring of the internal behaviour of what the authentic GoogleAuthUtil would have done. What matters to us is the output, namely having a token string.

 

#2 Create the custom runner

We have to declare, within a custom runner, the existence of our custom Shadow classes that can be used through Robolectric within the tests classes.

In our case, we have a single custom Shadow that we want to be loaded in the place of the authentic GoogleAuthUtil class.

 

#3 Use shadow class in Unit Tests

Having our shadow class and a custom runner that will load it, we can now use it very simply in our Unit Tests.

The first thing we have to do is of course declare the custom runner to use by using the @RunWith annotation.

Then, we also have to explicitly declare which shadows the class will use thanks to the @Config annotation, through the shadows parameters.

That’s it, whenever we will call GoogleAuthUtil.getToken() method in our tests, the framework will call the method within the shadow class, and as a matter of fact, will return « token » 

 

Conclusion

Shadows are very powerful extensions that let you enhance the Robolectric framework by providing additional or missing behaviour to it.

However, its setting requires few steps that have to be carefully followed to be able to use your custom shadows.

Last thing is: if you are doing a custom shadow, please submit it to the Robolectric project so anybody can benefit from your investment. 

#TechnologyFreeDay : #experiment

I am an entrepreneur, so I’m using computer, tablets and phones on a daily basis. I am also using, as anyone, my phone and other devices as an individual, to mainly interact with people on social networks, to take picture and so…

But lately, I’m also wondering about the over usage of all of this. Am I free in a sense that I use this technology to improve my quality and comfort, or am I addicted and enslaved by it ? This is a serious topic as I am an actor of this ecosystem.

So yesterday, I tried a new experiment that I called #TechnologyFreeDay. The idea is really simple : no computer, no tablet, no phone. All shut down for one big day (7th of February 2016, Sunday)

To be honest with you, it was an experiment worth to make. Indeed, it’s a strange feeling actually and all kind of questions arise.

#morning breakfast routine exploded

This starts on the morning when I used to be waken up by my alarm clock on my phone. This time, no alarm ringing whatsoever. Waking up with no constraint is really appreciable (That’s why I made this experiment on Sunday, there is no professional constraint). 

Then, just after waking up, usually I used to check mails, send some snaps, play youtube from time to time but also morning readings (books or magazine). This time, I prepared my breakfast (omelette), took my shower very quickly (due to not listening any podcast nor music) and decided to go and visit some cultural places. As I knew I couldn’t have access to my computer, I listed, the day before, few places I could go.

#museum opportunity

I took my car and park in the center Paris, at Saint Michel area.

I wanted to go on top of Notre Dame de Paris to enjoy the view, but when I reached, it was over crowded (2hours of queue). Is my time so worthless to waste it on a 2 hours queue ? I don’t think so…

So I went, by walk, to Panthéon. It was a 15 min walk, but completely different. No SMS to answer, no twitter timeline to check… I know the road by heart, but having the head up makes me see statues more precisely, look at the building in more detailed way, and looking to people too. I was more aware I can say.

#the non camera freedom

As a parisien, I know most places in Paris, but having the opportunity to visit them is a different topic. Usually, when I visit a place, as lot of people, I took pictures. But this time, my phone was shut down. I was still carrying it in my pocket, just in case of emergency. But I had no access to it, it was powered off.

Visiting a place knowing you can’t picture is somehow disturbing but also very pleasant. You are truly more focused on the painting you see, on the architecture. You know you can’t immortalize it on a picture, so you instinctively are more focused I would say, you just enjoy the paintings, the readings and all the statues.

It’s also funny, cause 95% of all the people you see hold their phone or camera, and took pictures (selfie or not). I saw someone rushing from painting to painting, just taking picture, without even looking at them firstly… It was funny. I also questioned myself, did I have the same behavior when I carry my camera? I hope not, because it looks so ridiculous.

#the bird feeder

Back home, I fixed the birdfeeder on my garden I did few days ago with recycled stuff. The birds are using it intensively, so lots of interest you may say 🙂 focused on a manual task here makes you feel more connected. Once fixed, birds were coming again few minutes later, that is rewarding 🙂

#GPS

On the afternoon, I decided to learn a new instrument. I saw few days ago a workshop happening in Paris to discover and learn the Siku, the Colombian flute. I decided to participate. And I tried to go without using any map, just with my orientation and… I failed 🙂 I reached the neighborhood by car, but I was unable to locate the street by using my orientation sense. I bearly know the area so I had to activate the GPS embedded in my car. I really wanted to avoid that, to avoid using that technology too but I realized that I made the effort to find the place on my own and was about to be late, so technology here was a needed companion (as I was 2 streets close, this helped me polluting less by reaching the place quickly instead of rounding…) I could have struggle more, ask people certainly but I decided to use the device to be helped and avoid wasting time. Instead of being addicted to it, I just used it when I needed it to make me save time. That’s all about technology, saving me time on things that are useless (like wasting time on traffic for what ?)

#music gather people

I went to this music workshop, and felt very connected to people, truly. 3 hours dedicated to discover this columbian instrument called Siku I would probably never try otherwise. I could have stayed home, watch a movie or play some game but went out of my comfort zone, meet people that share interest in this instrument and talk with them. There were kids as well as adults. Again, during the break, I saw kids playing with smartphone, adults sending message and so… It’s very interesting to observe all this behavior that I would probably do as well if I was not doing this technology free day. By observing them, I was in fact observing myself (in terms of behavior).

No phone, no messages, the only possibility left is to interact with human being. I’m close to people I guess even when I have my technology assistance, but without it, you are even more. You discover people, listen to their story, to their life, to their experiment, getting the most out of it. It’s priceless.

#the waiter

On my way back home, I decided to diner at a soup bar then to drink something, on a café facing Notre Dame I used to go with friends. I knew the director there, but our interactions was limited to courtesy ones.

I sat down on a table, and started to sip my drink, listening to live Piano music while looking at the huge Notre Dame monument. I had no choice but to focus on my senses: what I see, what I hear, what I taste. People were talking about an undefined number of topics, in any language I was able to understand thanks to the few languages I speak. Some were interesting, some were just useless. I guess that what happens when I gather with friends, sometime we probably talk about things that are pointless, sometimes about dreams and projects 🙂

Then a group of Asian tourists walk by the cafe, and the director says « come here, Paris is dangerous, it’s safer here » . I knew he was referring to the Paris attacks last November. So I started interacting with him and we talk quite a long about the events and he explained me how he dealt that night. His Café was highly exposed, he had 6 waiters there and all the customers…He barricaded the café and things… I know this could sound pointless, but if I was into my smartphone, I would probably never had this human interaction nor this real life testimony. Most importantly, I would never know this person, his name, and his point of view.

#back home

You are home now, but again, no mail to check, no message to send, no story or picture to share! Books are your best friends here. No blue light to keep you awake but the natural sleep cycle taking over 🙂

#conclusion

This was an excellent experiment I would probably try to make it weekly routine.

I really think we are starting to be weak with all this technology by not living the moment, but trying to artificially capture a moment that is uniquely aimed to be shared. So this experiment is all about «  toughening up ». No technology slavery or assistance unless it provides a real benefit.

There is one downside of this experiment I believe: it’s about close circle interaction. I wasn’t able to contact my family nor my friends and was unable to be contacted too. In case of emergency, this is really the worst. But this true disconnection really gives you the understanding of what should matter in life, and we are talking here about quality life.
As Paulo Coelho says in his book called Aleph : « Oublie que tu vas raconter cela aux autres. Le temps est ici. Profites-en. »

OpenPark – solving the Parking issue in the city

Recently, I was the studying the Beacon technology, and more precisely the Eddystone format.

Beacons are cheap devices that could be deployed anywhere that has a meaning for your business, for the city but even more importantly, for the user. (If you want to know more about beacons, I gave a talk at DroidconParis in november 2015, so check out the video).

I also participated at a hackathon on Intelligent Mobility early October 2015 in Bordeaux, France. There, I exposed two solutions for solving a global problem that lots of cities are facing (regarding the Public Parking Places).

ITSBordeaux

I made the local news 🙂

Problem

I live in a big city, and if you are a car driver living in that kind of big city, you should probably know that it’s a nightmare to find a public parking place available. We often waste a huge amount of time looking for a place, we get stressed, we pollute, we generate congestion. That should end, and for good.

Solution #1

Of one the solution could be to deploy and glue Beacons on the field and thus, equiped each public parking place with a beacon. The beacon would have an extra proximity sensor that could detect whether a car is parked above it or not. Thus, we could have, in real time, a network of availability places in the city.
Based on this real time data, a simple mobile application could then drive you to the nearest public parking place in the city.
It is a cheap investment for the city (glue-ing a beacon on each place) but could dramatically de-congestion the traffic.

Cons of solution #1

The solution #1 is cost effective but has some limitation. Firstly, an enhanced beacon has to be designed. This enhancement requires R&D to include a power efficient proximity sensor on top of the beacon.
Also, the beacon has to be rugged so is won’t break out on the car’s weight. Also, it has to be protected from weather (snow, rain…). So this enhanced beacon requires some technical challenges.

Solution #2

The solution #1 is a good candidate for solving our issue, but requires more engineering. The idea is to find a solution that is simple and easily deployable. That’s solution #2.

Instead of deploying and glue-ing beacons on each public parking place, what about having a beacon inside each car, in the glove compartment ? This beacon would stay is the driver’s car and paired with driver’s smartphone. So, whenever the driver is parked and is leaving his car, his smartphone is able to detect that he is moving away from his car (because beacon is all about range, so you can easily detect that you are in or out of the range of your beacon).

Having this information, your smartphone knows that your car is parked now and that in this precise location, the parking place is no more available.
Similarly, when you are getting back to your car, your smartphone will detect the beacon and then consider that you will leave the parking place. This information could then be broadcasted and anyone who is looking for a parking place in the area could be notified of that availability.

What’s next ?

I highly think that this will solve for good the issue of parking your car in any big city.
In term of investment, the city could give away a beacon for each driver, for free. The investment is really low compared to the issue it is solving (less pollution, less congestion, less stress, more happyness).

If you want to be part of that adventure and make the world a better living place, please contact me, I would be more than happy to have your collaboration.

 

 

 

OAuth2 and Google OAuth Playground

If you are a developer, chances are that you are using APIs that requires authorization to be used. That is especially the case with most of the Google APIs. So, you should at least be familiar with OAuth2.

The aim of this article is not to describe what OAuth2 is (there are dozens of literature on it), but simply a reminder of the standard, and pointers on how to use Google OAuth2 Playground which is a super easy interactive demonstration tool using Google APIs.

OAuth 2, reminder :

Roles

OAuth2 is not an authorization protocol, it’s a secure delegated access protocol. In this manner, you have to consider 4 distincts roles within this process : 

  • the ressource owner (typically you, or me or anyone…)
  • the ressource server where the owner stores his data (for instance entries in Google Calendar)
  • the client application (webpage, android app…) that will need to access the ressource of the owner (to display the Calendar entries for instance)
  • the authorization Server that grants access to the application (based on the owner approval).

Token

Whenever the client application needs to access a ressource, it first asks to the authorization server a Token (access or refresh token). This token is then used to access to the ressource located on the ressource server (the token could be passed in various way, but the most common is through the header of the request).

Scope

Token are used in a defined scope, which is a spectrum of ressources accessible with that token.

Google OAuth Playground

Google OAuth Playground is a sandbox where you can play with OAuth2 and the APIs that support it. For our use case, we will test the Proximity Beacon API which requires OAuth2.

There is already a description of the process for authorizing and Authenticating Proximity Beacon API requestsbut we’ll cover that with some screenshots.

Credentials

As described on the documentation, the first thing you need to do is to go to the Google Developers Console, create a project, activate the Google Beacon API, then go to the Credentials Section in order to get a client ID for a web applications (that we’ll use for the Playground)

1.Credential

2.Credentials

Be carefull to set https://developers.google.com/oauthplayground as a redirect URI

PlayGround

Go to the the OAuth 2.0 Playground and configure the OAuth Credentials (generated previously from developer console. Copy paste it there, as shown below)

3.OAuthConf

On the left side menu of the Playground, you have to set the scope for the Proximity Beacon API into the field labeled Input your own scopeshttps://www.googleapis.com/auth/userlocation.beacon.registry

4. Scope

As a result, the token will be generated and automatically used for next steps.

5.Token

Now, all the magic comes, you can request your API that request authorization (for instance https://proximitybeacon.googleapis.com/v1beta1/beacons)

6.Request

As you can see, you can add headers, add request body and so… In a word, you can easily test the API you are interested in and see the full result (header & body) 🙂

You’ll get the response of your request which requires authorization 🙂

7.response

Do not hesitate to over use this playground, it should definitely be used as part of API exploration (more than reading static documentation 🙂

Citation

Pursuit of Truth

The true value of a man is not determined by his possession, supposed or real, of Truth, but rather by his sincere exertion to get to the Truth. It is not possession of the Truth, but rather the pursuit of Truth by which he extends his powers and in which his ever-growing perfectibility is to be found. Possession makes one passive, indolent, and proud. If God were to hold all Truth concealed in his right hand, and in his left only the steady and diligent drive for Truth, albeit with the proviso that I would always and forever err in the process, and offer me the choice, I would with all humility take the left hand, and say: Father, I will take this one—the pure Truth is for You alone.

 — Gotthold Ephraim Lessing

En passant

Android SDK Tools vs Platform Tools vs Build Tools

Well, in order to avoid being confused if you are and android developer, this is just a reminder that hopefully will makes things more clear. 

Typically, SDK Tools are platform independent whereas Platform tools, obviously, support the features of the latest Android Platform. Build Tools gather tools that will produce your signed Apk.

you can get more detailed information from the official documentation

SDK Tools

Roughly, SDK tools include all the tools that you need to develop for android; 

That includes the SDK manager (to download android SDKs), development tools such as AVD (android virtual devices), Image tools (such as draw 9 patch), Debugging tools (such as ddms), monkey runner and so…

It is not an exhaustive list of course. You can open the folder on your machine to get all of the tools.

Platform tools

These tools are updated for each new android sdks release and is backward compatible. The platform tools include for instance ADB which is a bridge that allows you to communicate with your android device or emulator. ADB has to know how to communication with the Android version that is hosted on your device.

Build Tools

The build-tools are used to build your application, that is to produce your APK.
Release notes here and nicely detailed build process here.

État

Elon Musk biography – contrasting but inspiring

From time to time, I have the luxury to take some vacation. This summer (2015), I spent some time on the mediterranean coast in Turkiye and took with me the Elon Musk biography from Ashlee Vance as a beach book. Well, what a life !!

Elon Musk Biography from Ashlee Vance

(Re)Discovering what Elon Musk has done is quite disturbing, in a sense that the phrase « nothing is impossible » took another meaning while reading the book. The guy is so motivated by changing the world that you can not remain insensitive to his moves. Life is definitely too short, but it could appear that some people are trying to make the best out of it. And this is absolutely required.

Not only he has a greater vision on changing rigid industries (such as automotive or aerospace) for people’s benefit, but he is also a tremendous risk taker, investing all his money into his companies and the products he’s building. You can’t do that if you don’t BELIEVE in whatever you are investing your time to. It once again confirms what I experienced from myself, that « money is not an asset, it’s a flow ». It has to be invested in a way that it could help you support your projects and then generate great value for humankind.

However, there is also a side of the persona that I truly dislike. I have a very high respect for every human being, whoever he or she is. And I felt, from time to time, very shocked on how Elon Musk behave with people, pushing them under extreme stress and consuming their time for a bigger cause. Life is beautiful, and even if you are building amazing products, I highly believe that you have to let people enjoy their life, enjoy what matters for them. It’s their lifes, not yours, let them be. For instance, at page 177, it appears that one employee has missed an event or meeting to witness the birth of his child. What a beautiful event not to miss. However, Elon Musk was very disappointed and said «That is no excuse. you need to figure out where your priorities are. We’re changing the world and changing history, and you either commit or you don’t ».
It’s perfectly fine if you invest all your time to something, but this has to be a free choice of yours, not a choice under pressure.
I am very careful about this aspect and relationship with people; and I believe that success or commitment doesn’t required you to behave like Elon Musk or Steeve Jobs towards employees.

No one is perfect of course, and anyone is free to like or dislike some aspects of your peers. But you have to see these judgments as a learning and keep the best of it for yourself. One of the other quality that I appreciate from Elon Musk is his ability to take decisions very quickly. I feel sometime very annoyed to take a decision, especially for useless stuff like buying clothes on store or choosing the menu at restaurant. Well, this is in a way very ridiculous because you are consuming time in predicting what could be the best for yourself without being sure. And to be honest, you could never have the answer of that prediction in advance. The only meaningfull step is to take decision quickly then pivote if your experience is not as expected.

The book is full of learning that you could apply to yourself, through the protagonist’s life (if you are willing to extract whatever matters to you).
So I definitely recommend you to read the biography. You will feel inspired in a high level, and this is all the more helpful if you are an entrepreneur willing to make a better world with amazing products.

Gradle, dependency and Local Repository

If you are an android developer, working on non collaborative projects on your own computer, you have definitely faced the situation where you need to use some piece of software among many projects (mainly utils).

This situation is nothing else than a dependency requirement. So what are our choices to make it smooth ?

step 1 : create an Android library module

I am sure many of you are making copy/paste of piece of sofware from one project to another. Who didn’t, right ?
First of all, get rid of this archaic habit and simply put this reusable software into an android Library module . That’s easy and cheap. Moreover, that gives you the power to make your software evolve peacefully, with adding quality and consistency through time.

step 2 (optional) : make it public and deploy it on maven central

This module is hosted on your computer. You can make the choice to publish your library into github and make the source available to the world. Then, you can simply deploy your artifact to maven central and easily fetch it into any of your project (and let others use it too). To do so, please read my previous article where I detailed the entire process of publishing and deploying an open source project.

But you probably won’t go that far. Your need is to keep your software private but benefit from the gradle dependency mechanism.

step 2 : keep it private

You will probably keep this peace of software private for any valid reason (high end technology you haven’t patented yet oO … or … software not high quality enough …or… pure selfishness…) Whatever the reason is, it’s ok, it’s your decision 🙂
However, even if it is private, do not forget to version your source code into private repository.

step 3 : publish on local directory

The idea here is to publish your artifact into a local directory of your file system. Bear in mind that this directory (used as repository) will host many versions of the same library, and even multiple private libraries, so don’t forget to backup it (using dropbox or google drive for instance) in case you switch computer.

Based on the Gradle Repository Handler documentation, gradle supports many repositories where your project can fetch artifacts. Among them, you can find jCenter(), mavenCentral(), mavenLocal() or any maven() custom repository.

Why don’t we use directly mavenLocal() as our local repository ?
We could of course install our artifact into mavenLocal (/home/.m2/repository) but this repository has another goal. It’s mainly used for caching artifacts to save network requests. Moreover, we loose our sync-ing requirement. Indeed, there is no need to backup the the .m2 folder, it’s just non sense.

So we need to choose a local folder of our choice (for instance /Users/turhan/LocalRepository/).

step 3.1 : configure your library’s build.gradle

We have to configure our library’s build.gradle to specify the directory where to deploy our artifact

We have here created the uploadArchives task by defining the repository url where the artifact will be deployed by maven(here it is a local file:// path).
As you can see, we have to include the maven plugin  (highlighted on the first line) so the mavenDeployer can work.
Finally, don’t forget to specify a group, an archiveBaseName as well as a version. And for each release, do not forget to increment the version  (better put it into a variable inside grade).

step 3.2 : upload your artifact

So now, to deploy our artifact into our local directory called LocalRepository, we simply call the task

step 4 : fetch your artifact into your project

step 4.1 : configure the repository url

On any other other project of yours, open the top build.gradle. We will specify there the path to our local repository

step 4.2 : import the dependency

Now, we can easily define our library as a dependency, such any other dependency. Gradle will look into each repositories we have defined (mavenCentral() and or custom local repository)

Conclusion

We could have installed a Nexus repository locally, but to be honest with you, this is overkill (credentials + web server & so) for our need (non collaborative projects). We need something that could be setup quickly, something that could be backuped easily.
The setup detailed here is not complicated at all and gives you the opportunity to manage your private dependencies easily.
I hope you could save some time with that and make your development process more smooth.

Enjoy 🙂