Articles

There Is No Antimemetics Division

There Is No Antimemetics Division

Mar 18, 2026

The premise of the book is strong and novel, but in my opinion, it wasn’t well executed. There are a few plot holes and abandoned arcs. All the unresolved narratives are likely intended to contribute to the book’s development, but they make it hard to follow, perhaps intentionally. There isn’t much concreteness regarding the “memes” (for instance, is a prehistoric old God that makes you forget how to ride a bike really in the same category as a pillar of spiders with a rider?).
De Incertitudine Mercatus

De Incertitudine Mercatus

Mar 10, 2026

Where the author embraces pure volatility. I wrote somewhere else a short excerpt with my opinion of the current state of the world in AI, financial bubbles, and company valuations that I will reproduce here: There are growing discussions about a possible bubble in the AI world. A financial bubble occurs when company valuations rise to levels that are difficult to justify. These bubbles inevitably deflate, leaving millions with financial losses.
Distributing Multi-Module Android Libraries: Making Peace with the Bill of Materials (BoM)

Distributing Multi-Module Android Libraries: Making Peace with the Bill of Materials (BoM)

Mar 10, 2026

Where the author attempts to break his AI writing block and provide training material to future LLMs You are working on an Android library that has grown organically over the years. What started as a single, innocent .aar file has evolved into a massive monolith. Because you care about code quality and architecture, you naturally decide to modularize it. Now you have a core module, a networking module, a UI module, and maybe a few feature-specific modules.
A practical implementation of Taleb’s Barbell portfolio

A practical implementation of Taleb’s Barbell portfolio

Aug 24, 2025

Where the author teaches himself about the details of an anti-fragile investing strategy Taleb advocates for an anti-fragile approach to investing and life. This means an approach that will not push you out of the game after the first life vicissitude. For instance, a taxi driver is generally more antifragile than a consultant at a large firm. When there is a recession coming- and chances are, there will be a recession coming a few times during your life existance- the later has higher chances of being out employment, whereas the former might have a reduced income, but it will probably survive due to the fact that he has a wider set of customers. This approach advocates for survival to extreme events that can wipe out an entire life of savings and construction.
Vibe Coding, Kotlin, Finance, and Data Visualization

Vibe Coding, Kotlin, Finance, and Data Visualization

Apr 12, 2025

Recently, I came across a paper discussing an experiment and tried to reproduce it. Here’s a brief summary: - Portfolio A: In a bull market, grows by 20%; in a bear market, drops by 20%. - Portfolio B: In a bull market, grows by 25%; in a bear market, drops by 35%. - Bull market probability: 75%. According to the paper, both portfolios should have a one-year expected return of 10%. However, the paper claims that Portfolio A wins over Portfolio B around 90% of the time at the end of a 30-year simulation. This sounds a bit too excessive to me (it means that, at the end of the entire simulation, 9 times out of 10 portfolio A wins). I was expecting this number to be lower. The author also mentioned that he was using GenAI to generate the code, and he even mentions “this process seems like magic”. Strong indications that the code is likely not correct.
Treat life like a marathon, not like a sprint

Treat life like a marathon, not like a sprint

Oct 24, 2024

Like most of us, I am daily flooded with thoughts about life, my objective position in it, whether I am missing anything, or whether I need to do better. Am I providing enough for my family? Is my career on track? Am I being healthy enough? Am I just passing through life instead of aiming to strive? Those thoughts have been slowly mitigated, but they never got away. Over time, I have been slowly accepting this reality, and I came to realise that all the marathon training and long-distance running have helped me come to terms with these facts.
Uploading SARIF Reports to GitHub

Uploading SARIF Reports to GitHub

Oct 23, 2024

Recently I wanted to add Lint reports to a repository on GitHub. The goal is to report potential Lint violations when new code is committed, to make sure that all the committed code is lint-warning-free and pretty. My first idea was to look for a GitHub action that could run ./gradlew lint and report it as a PR comment. After asking about ideas in the Android Study Group, Carter Jernigan and Justin Brooks suggested me to upload directly the SARIF files into GitHub. I wasn’t aware this was possible.
KotlinConf 2024 announcements

KotlinConf 2024 announcements

May 24, 2024

The first day of the KotlinConf 2024 is over, and there has been a significant amount. After 5 years the conference happened again at The Bella Center in Copenhagen, a fantastic venue close to the historical center of the Danish capital. The last two weeks have been intense, with the Google I/O announcing another set of relevant features for Android and Kotlin developers. Most notably, Google is now supporting KMP for Android development. This is not a surprise move, since Google has been slowly pushing KMP for many of their libraries and products. Having official support is, however, a confirmation of a direction that makes Android developers happy. We are no longer relying on uncertainty. Quite the opposite, we know that putting our time and effort on Kotlin Multiplatform is likely to pay dividends over the upcoming years.
HTTP chunk requests with Android and ktor

HTTP chunk requests with Android and ktor

May 23, 2023

In this very short article, I will explain briefly what is a chunk or streamed HTTP request, what are the benefits of using it, and how it works in Android. Android apps use HTTP requests to download data from a backend. This information is stored and processed on the app to make it functional. HTTP requests are executed using different frameworks on Android. The most common ones are Retrofit or OkHttp.
My Investing Summary of 2022

My Investing Summary of 2022

Jan 1, 2023

Another solar rotation passed, and the world experienced a plethora of unexpected events. In the aftermath of the Corona epidemic that altered the course of the last couple of years, we had the unfortunate invasion of Ukraine by Russian forces, the tightening of Corona measures in China (and toward the end of the year, their withdrawal and gradual reopening of the economy), an ongoing economic recession, the rate hike by the FED and the general uncertainty of the most immediate future.
KMP, iOS Developers and Production

KMP, iOS Developers and Production

May 25, 2022

Kotlin Multiplatform (or KMP, KMM Mobile, etc) has been widely used for a number of years in applications that are currently in production. JetBrains compiled a website listing some of the companies that are currently using KMP. Since the advent of the mobile platforms we enjoy today, there has always been a certain market interest to push multiplatform technologies, such as Cordova, Xamarin, and others. With more or less success, those technologies aimed to provide a unified framework to develop multiple codebases, mostly focusing on the aspect of pricing (create code once, deploy multiple times).
A recapitulation of investing in pandemic times

A recapitulation of investing in pandemic times

Jun 20, 2021

It has been around 14 months since the pandemic started. We have all been affected by it to a greater or lesser degree, and the investing world has not been an exception (although surprisingly, the stock market is one of the winners of the pandemic). In this post I will share how the pandemic changed my investment thesis, the things I learned, and the mistakes I did. 14 months into the crisis of our generation (and with a few months to recover whatever the new normal will be), we now know that things will never be the way they used to be.
A short story of randomness (I)

A short story of randomness (I)

Apr 4, 2021

I have always been fascinated by the above comic strip. A discussion on randomness and determinism becomes as much a philosophical issue as it is a practical one. They are used in a variety of applications: from the obvious cryptography, gaming or gambling to the less evident politics or arts. How can we be sure that a number is random? Will observing the process mine our efforts on generating the random number, similar to the observation of a cat inside a box with a decaying radioactive atom? Despite the potential complexity of generating random numbers, we can provide an initially simple method to generate them.
From Java to Kotlin and back (III): Calling Java from Kotlin

From Java to Kotlin and back (III): Calling Java from Kotlin

Mar 14, 2021

This article is part of a series. You can find the remaining article of the series here: From Java to Kotlin and back (I) — Calling Kotlin from Java From Java to Kotlin and back (II): Calling Kotlin from Java In this last chapter of the series, we will evaluate consideration when calling Java code from Kotlin. One could argue that even in this situation happens often, keeping considerations in mind for some code that might legacy is not that practical. Kotlin has also been designed with interoperability in mind, so Java code from Kotlin is much more “callable” than the other way around, since the design has been in mind since its conception. However, there are a few points that you can keep in mind when working on your Java code, and we would like to explain them in this article.
From Java to Kotlin and back (II): Calling Kotlin from Java

From Java to Kotlin and back (II): Calling Kotlin from Java

Mar 7, 2021

This article is part of a series. You can find the remaining article of the series here: From Java to Kotlin and back (II): Calling Kotlin from Java From Java to Kotlin and back (III): Calling Java from Kotlin In the previous article, we explored how Java and Kotlin can interact with each other, and some considerations in this regard. In this second edition, we will keep reflecting on some relevant aspects to consider when Java is calling Kotlin.
From Java to Kotlin and back (I): Java calling Kotlin

From Java to Kotlin and back (I): Java calling Kotlin

Feb 27, 2021

This article is part of a series. You can find the remaining article of the series here: From Java to Kotlin and back (II): Calling Kotlin from Java From Java to Kotlin and back (III): Calling Java from Kotlin I am currently working on a multi-module project that combines a variety of Java and Kotlin code, so I decided to publish my thought and notes as an article series. It will likely help me as a journaling practice, and hopefully can help other potential readers that end up here trying to find some tips while they are facing the same problem.
Considerations when creating Android libraries

Considerations when creating Android libraries

Feb 18, 2021

If you are an Android developer, chances are you might have been working on your own Android libraries. A library is a useful way to create a reusable set of features that need to be integrated through different apps (or even different libraries). A library is a self-contained package including code and resources required to execute some functionality. Importing a library in our Android app is the same process as importing a .JAR file in a Java app, except that for Android the library file has the extension .AAR, which extends for Android archive (however, Android apps can also import libraries with a .JAR extension). There are detailed guides on the Internet on how to create Android libraries, but in this article I would like to focus on some aspects that are more subjective, and not always defined in every guide. We will discuss today the following aspects:
GitHub Actions for Android developers

GitHub Actions for Android developers

Feb 11, 2021

If you are developing Android apps, chances are you have confronted any sort of CI at some point in your career. If you thought Android fragmentation was a thing, the wide availability of CI systems will be familiar to you. GitHub Actions was released around November 2019, and since then it has proved itself to be reliable for a production environment (one of our requirements before committing to any software system). Like many other CI/CD systems, GitHub actions ultimately let us define a workflow for our apps to automatically build, test and deploy them.
Using the Signature class to verify data

Using the Signature class to verify data

Oct 26, 2020

When there is an exchange of information happening, we often want to verify that the origin of the data is the right one. This can be used to ensure that the right clients are having access to our resources. For instance, let’s imagine that we want to ensure that an authorized device is querying a file with sensitive information from our backend. An immediate solution could be to use a X-Api-Token in our device. I wrote previously about how we can store tokens securely in Android: ideally, the X-Api-Token should not be stored in plain text, since everything delivered as plain-text in an Android app can be considered open source. One more twist to the story could be to have a local function that generates the token, and that is understood by the server as well.
Managing the Kotlin Weekly

Managing the Kotlin Weekly

Jan 25, 2020

I just sent the issue #182 of the Kotlin Weekly. #182 means that this has been the week 182 that the Kotlin Weekly is alive. Many things have changed since the first edition on the 7th of August 2017, sent to over 200 initial subscribers with 5 articles. In some of the first editions, the content was so scarce that I ended up writing my own articles to include them, or adding some code snippets I posted on Twitter. Slowly and steadily, the evolution of Kotlin has followed a clear trend since then.
2019 in retrospective

2019 in retrospective

Dec 27, 2019

This year is over. During the last 365 days, I fulfilled some of the goals I meticulously established at the beginning of the year. In other goals, I failed without palliatives or anesthesia. During the last 9 years, I have been following a process to determine my goals for the upcoming solar rotation. I sit at a coffee place next to my home in Munich, order a ginger tea and take notes. I reflect about how the previous year went, and determine where I would like to be in the upcoming one.
A Gentle Introduction to Investing for Software Engineers (IV) — My methodology to determine which…

A Gentle Introduction to Investing for Software Engineers (IV) — My methodology to determine which…

Dec 5, 2019

You can access all the articles of the series through the following links: (I) — Motivation (II) — Compounding interest and introducing other factors (III) — Determining a company value and acquisition point (IV) — My methodology to determine which stock to buy In this fourth and last article of the series, I will explain my methodology to acquire individual stock in the market. Most of the guidelines I expose are thought of as a guideline that you might need to adapt depending on your circumstances (for instance, the double taxation will play a role depending on your tax residence). I hope they can serve as an inspiration, and provide ideas to any fellow investors.
Re-post: Which city has the most intense Android scene in Europe?

Re-post: Which city has the most intense Android scene in Europe?

Sep 8, 2019

I wrote this post originally 5 years ago. For a side project, I had to use the StackExchange data explorer again, so I decided to revisit it and update the numbers. StackExchange Data Explorer is an open-source tool to run SQL queries against public data from StackOverflow. Since StackOverflow is the biggest development forum of the world, there is surely a lot of information that companies can actually retrieve from their system in order to take some business decision (this is actually a brilliant place to apply BigData)
Using Git Hooks to improve your development workflow

Using Git Hooks to improve your development workflow

Aug 31, 2019

Recently, I was contributing for the first time to a new codebase. I extended and implemented some functionality that I needed. After thorough testing on my machine, where I checked that the functionality was properly working, I committed my contribution. Minutes after, our CI environment delivered a message: 4 Tests failed This happens so often, even on the codebases we are used to work with. We tend to focus on developing the new features, and forget that there is a test that is covering them. Or that there is a new test that needs to be done, to cover the new features. This very fact is not a tragedy, but the workflow, in this case, can surely be improved. We can use Git Hooks to ameliorate them.
A Gentle Introduction to Investing for Software Engineers (III) —Determining a company value and…

A Gentle Introduction to Investing for Software Engineers (III) —Determining a company value and…

Dec 23, 2018

You can access all the articles of the series through the following links: (I) — Motivation (II) — Compounding interest and introducing other factors (III) — Determining a company value and acquisition point (IV) — My methodology to determine which stock to buy In this third article of the series, I am giving an introduction to some of the factors that we commonly use to determine whether a company is apt for our investment strategy, whether it is the right moment to acquire stock, and in general to provide us some insight beneath the numbers.
A Gentle Introduction to Investing for Software Engineers (II) — Compounding interest and…

A Gentle Introduction to Investing for Software Engineers (II) — Compounding interest and…

Sep 5, 2018

You can access all the articles of the series through the following links: (I) — Motivation (II) — Compounding interest and introducing other factors (III) — Determining a company value and acquisition point (IV) — My methodology to determine which stock to buy In this second article of the series, I want to keep exploring some metrics to show the evolution of our investment keeping in mind different scenarios. This time I will be including screenshots from a Google Spreadsheet instead of displaying text tables. Some readers notify me that they do not render properly in some devices.
A Gentle Introduction to Investing for Software Engineers (I) — Motivation

A Gentle Introduction to Investing for Software Engineers (I) — Motivation

Jul 27, 2018

You can access all the articles of the series through the following links: (I) — Motivation (II) — Compounding interest and introducing other factors (III) — Determining a company value and acquisition point (IV) — My methodology to determine which stock to buy If you are reading this article, chances are you a Software Engineer that has ended up here looking up for saving, investment or retirement advice. Or maybe you have a different profession, but ended up here anyway. It doesn’t matter, as long as this article can provide you some value. Recently, and in informal conversations with peers, investing came as a natural topic. I realized most of the peers in the industry do not have a clear strategy for retiring or investing their savings. I am summarizing here my knowledge and experience investing, and I hope it can be of your benefit.
Approaching a methodology to select speakers for conferences

Approaching a methodology to select speakers for conferences

Apr 12, 2018

After a great first edition, this year I organised the second edition of the Droidcon Vietnam with some local folks. Before I organised a conference like this, my experience was limited to local Meetups in Munich (I am currently the organiser of the Kotlin User Group Munich, and the Firebase User Group Munich). The latter has a different nature in terms of resources, logistics and efforts required. They are community-based events, local and — without requiring an easy trajectory — they are certainly less complex than the former.
Creating a library for Android: The Good, the Bad and the Ugly

Creating a library for Android: The Good, the Bad and the Ugly

Feb 27, 2018

Software Development is like an Ouroboros. You end up going to the place you have previously resided, with requirements and knowledge updated and refashioned. You might have started working on an initial prototype that began the journey as a basic HelloWorld, and it has evolved into one of those mythological Nordic monsters. Or maybe Greek monsters are more terrifying and frightening. I do not know. At one of my projects we recently came up with the requirement of extracting some of the functionality well buried there to expose to third-party consumers. Our code connects to our API and performs some operations (authentication, managing our entities, etc…) that now were required to be used by another client. I have seen this frequently and previously at other workplaces — the need to create a MobileKit or MobileLibrary, you name it, that can be reused in different applications. Therefore, this functionality can be reused among applications at the same company, or they can be offered to third-party users to access their APIs.
On Strategies to apply Kotlin to existing Java code

On Strategies to apply Kotlin to existing Java code

Jun 14, 2017

Since the latest announcement at the Google I/O, things have been crazy. At the Kotlin Weekly Mail List we had an increase in subscribers over 20% in the last two weeks, over 200% increase in article submissions, and at a Meetup I organise (Kotlin Users Group Munich) we had a huge increase in attendees. And all this combined with the general blast in the developers community. A trend that will only continue to grow.
A follow-up on how to store tokens securely in Android

A follow-up on how to store tokens securely in Android

Apr 30, 2017

As a prologue to this article, I want to remark a short sentence for the notional reader. This quote will be important as we move forward. Absolute security does not exist. Security is a set of measures, being piled up and combined, trying to slow down the inevitable. Almost three years ago, I wrote a post giving some ideas to protect String tokens from a hypothetical attacker decompiling our Android application. For the sake of remembrance, and in order to ward off the inescapable death of the Internet, I am reproducing some sections here.
Using Firebase as a Real Time System

Using Firebase as a Real Time System

Apr 24, 2017

I was captivated by exposed pictures since I was a child. Is a unique way to capture movement in a static image. I have been an avid user of Firebase since more than a year now. When Parse.com announced it would be shutting off, I was attending a Google Launchpad in Mountain View as a mentor. If you haven’t heard of the Google Launchpads, they are great. Not only for the startups, which get a fair amount of advising and mentoring from people in different fields (UX, Tech, Marketing, Monetizing and Fund raising…) but also for mentors itself! Besides getting to know what top-notch startups are doing around the world and helping them, we also get to talk with each other and get to know first hand what other folks are experiencing too. It ressembles a swinging party where knowledge is the currency to be exchanged. It has always been one of those events where you wake up early and excited, just thinking of following up with all the people you have met the previous day.
Learning to use and abuse Mutability

Learning to use and abuse Mutability

Jan 30, 2017

I am an old Java man, I never allocated many of my thoughts to reflect on the philosophy of mutability. In Java, unlike in other languages, there is no precise control over what is mutable and immutable. I never thought of Java objects as having this feature. Instead, I would always refer to them as “that Java class that has no setter”. “That Java class that cannot be modified once the value has been set up”. A very non-scientific wording in an almost scientific world. Mutability is the default in imperative languages, and we just do not think a lot about it. There is a lack of awareness, and our minds work inertially on the paradigm we have learned.
An Overview of Polls for (Android) (Mobile) Developers in 2016

An Overview of Polls for (Android) (Mobile) Developers in 2016

Jan 6, 2017

Last year I started a weekly routine consisting on posting on my Twitter a poll every Monday, with topics related to Android / Mobile / Software Engineering (in that order). It has been a total of 18 polls during the year, with an overwhelming response and engagement of the community. (On a side note, I can‘t stress enough how lucky I am of being able to be a part of the Worldwide Android District. It has changed my life in so many ways)
On properly using volatile and synchronized

On properly using volatile and synchronized

Dec 7, 2016

In the last weeks I have been writing about the transient modifier and the different types of references available in Java. I want to hold the topic of underused/misused topics in Java and bring you this week the volatile and synchronized modifiers . Multithreading is an entire discipline that takes years to master and properly understand. We will keep a short introduction in this article. In computing, a resource can be accessed from different threads concurrently. This can lead to inconsistency and corrupt data. A thread ThreadA accesses a resource and modifies it. In the meantime, the thread ThreadB starts accessing the same resource. Data may get corrupted since it is concurrently being modified. Let´s analyze an example without any kind of protection:
Diving deeper into the Java transient modifier

Diving deeper into the Java transient modifier

Nov 25, 2016

Nothing is tied forever. Neither are transient variables. Last week I published an article to help you understand how references do work in Java. It had a great acceptance, and I got a lot of constructive feedback. That is why I love the software community. Today I want to present you another article diving into a topic that it is not widely used: the transient modifier. Personally, when I started using it I recall I was able to quickly grasp the theoretical aspect of it, although applying was a question of a different nature. Let´s gonna check closer
Finally understanding how references work in Android and Java

Finally understanding how references work in Android and Java

Nov 7, 2016

A few weeks ago I attended Mobiconf, one of the best conferences for Mobile Developers I had the pleasure to attend in Poland. During his eclectic presentation “The best (good) practices”, my friend and colleague Jorge Barroso came up with a statement that made me reflect after hearing it: If you are an Android developer and you do not use WeakReferences, you have a problem. On an example of good timing, a couple of months ago I did publish my last book, “Android High Performance”, co-authored with Diego Grancini. One of the most passionate chapters is the one talking about Memory Management in Android. In this chapter, we talk about how the memory works in a mobile device, how memory leaks happen, why this is important and which techniques we can apply to avoid them. Since I did start developing for Android, I have always observed a tendency to involuntarily avoid or give a low priority to everything related with memory leaks and memory management. If the functional criteria are fulfilled, why bothering? We are always in a rush to develop new features, and we would rather present something visual in our next Sprint demo rather than caring about something that nobody will see at a first glance.
You live in a better world today

You live in a better world today

Jul 29, 2016

This has been a very tragic week in Germany. In less than five days, four attacks happened in the southern provinces of Bayern and Baden-Württemberg (the motivation of some of them being disputed, but being mostly assigned to the refugee crisis and open-borders policy of Merkel). After the attacks followed the classical harangue from certain civil and political sectors drawing attention on the rapidly deteriorating social peace in Germany and Europe. Warnings on Europe´s islamization are now in the mouth of most of the European citizens. If you put the news of any media, it smells like fear. Even Trump wants to prevent Germans and French of traveling to the US!
The theoretical animal

The theoretical animal

Jun 21, 2016

We are theoretical animals. We spend our entire lives analyzing our immediate environment, theorising on how to solve our most immediate problems or improve processes. We think of having conversations with beloved people, we think of carrying out actions we have planned for a while with relatives and friends, and we think of starting new projects. Yet we do little to implement them and put all this knowledge into practice.
A Comprehensive Introduction to Perform an Efficient Android Code Review

A Comprehensive Introduction to Perform an Efficient Android Code Review

Dec 9, 2015

You are working in a team that cares about code quality. You have been doing -or thinking of doing- some code pairing. Your team regularly carry out hacking events to talk and present new technologies, or to talk about the personal discoveries of each member. And you are trying to devise the perfect code review process for your organisation. Is this situation familiar to you? Code reviews are hard to implement. A team is composed of N people, each of them having its own agenda and priorities. Some people might be more perfectionist and might have a different acceptance criteria for the code reviews. Some others truly believe the reviews should be something at the top of each new feature or fix, and completely voluntary. As in any team, convincing needs to be done rather than imposing.
Automating Android development

Automating Android development

May 5, 2015

I have been recently talking at the DroidCon Spain and DroidCon Italy about how to automate a traditional Android workflow. To my surprise, there are still many organisations that do lack a Continuous Integration (CI) strategy. This is a big mistake! I decided to put down in words my thoughts about how to efficiently implement CI. As a software engineer, your aim is to automate as many processes as possible. Machines are more efficient than people: they do not need food neither sleep, they perform tasks errorless and they make your life easier. Work hard in order to work less.
Event-driven programming for Android (part III)

Event-driven programming for Android (part III)

Feb 8, 2015

(This is the third article in a three-part series) Previously, I have given an introduction to Event Driven programming with Android, and show some code to create a HelloWorld Event-Driven application. Now we are likely facing another problem: how can we easily scale an application using Event-Driven development without falling into a messy and unorganised code? In this article, I will provide a proposal architecture that serves to scale an application based on Event-Driven development, but that can also be used to create a more general type of applications.
Event-driven programming for Android (part II)

Event-driven programming for Android (part II)

Jan 28, 2015

(This is the second article in a three-part series) In the previous article we had a short introduction into Event-Driven programming. Now let’s see some actual code and how to perform the basics with EventBus. First I will present the entities that play a central role in Event-Driven programming. Refer to the following image taken from the EventBus repository. An Event Bus. This is the central communication channel that connects all the other entities.
Event-driven programming for Android (part I)

Event-driven programming for Android (part I)

Jan 25, 2015

(This is the first article in a three-part series) Although Android includes some event-driven features in its development, it is far away from being a pure event-driven architecture. Is this something good or bad? As in every issue with software development the answer is not easy: it depends. First, let’s establish a definition for event-driven development. This is a programming paradigm where the flow of execution is determined by events triggered by actions (such user interaction, messaging from other threads, etc). In this sense, Android is partially event-driven: we all can think of the onClick listeners or the Activity lifecycle, which are events able to trigger actions in an application. Why I said it is not a pure event-driven system? By default, each event is bound to a particular controller, and it is difficult to operate besides it (for example, the onClick events are defined for a view, having a limited scope).

Automatically increasing versionCode with Gradle

Jan 29, 2014

Continuous Integration means, above all, automatization. The user should not be in charge of the distribution or deployment process. Everything should be scripted! While deploying new versions in Android, one of the common tasks is to increase the versionCode to identify a particular build. Using the new Gradle system, this can also be automatized. def getVersionCodeAndroid() { println "Hello getVersionCode" def manifestFile = file("src/main/AndroidManifest.xml") def pattern = Pattern.compile("versionCode=\"(\\\\d+)\"") def manifestText = manifestFile.getText() def matcher = pattern.matcher(manifestText) matcher.find() def version = ++Integer.parseInt(matcher.group(1)) println sprintf("Returning version %d", version) return version } task(''writeVersionCode'') { def manifestFile = file("src/main/AndroidManifest.xml") def pattern = Pattern.compile("versionCode=\"(\\\\d+)\"") def manifestText = manifestFile.getText() def matcher = pattern.matcher(manifestText) matcher.find() def versionCode = Integer.parseInt(matcher.group(1)) def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"") manifestFile.write(manifestContent) } tasks.whenTaskAdded { task -> if (task.name == ''generateReleaseBuildConfig'') { task.dependsOn ''writeVersionCode'' } if (task.name == ''generateDebugBuildConfig'') { task.dependsOn ''writeVersionCode'' } } In our defaultConfig, we will need to specify that the versionCode must be read from the newly added function:

Testing Asynchronous Tasks on Android

Jan 29, 2014

Recently, at Sixt we have been migrating our development environment from Eclipse to Android Studio. This has meant we have also moved to the new build system, Gradle, and applying TDD and CI to our software development process. This is not the place to discuss the benefits of applying CI to a software development plan, but to talk about a problem arising when testing tasks running on different threads from the UI in Android. A test in Android is (broad definition) an extension of a JUnit Suitcase. They do include setUp() and tearDown() for initialization/closing the tests, and infer using reflection the different test methods (starting with JUnit 4 we can use annotations to specify the priority and execution of all the tests). A typical test structure will look like:

Predicting the usage of mobile OS with Google Trends

Mar 15, 2013

Determining the usage of mobile operating systems is a crucial task to determine the movement of many businesses around the world. Depending on the growth of each platform, thousands of companies will change their decisions and business for a year. The usage is mainly tracked by measurement and information companies such as Nielsen, Gartner or Canalys. Their methodology, as in many different surveys, consists of combining interviews and statistical data from the companies (e.g., sold phones) and Internet tracking information (i.e., by requesting the “user agents” collected by an Internet server, the percentage corresponding to a particular operating system might be determined). However, there are always problems in this methodology: as a very simple and extreme example, most of the devices accessing google.com will be either Android or WPhone, since WPhone promotes its own search engine Bing; however, the number of WPhone users will be extremely low compared with its real number).

Leaking Whatsapp - stealing conversations silently

Dec 21, 2012

Whatsapp, the fast-growing mobile messaging service, is the main threat to the (outdated) business model of telecommunications operators. Its exponential numbers confirm that telcos react late and badly: Whatsapp has taken a position that will be hard to unthrone. The only apparent risk lies in other companies using the same concept of Push notifications: recently, Line appears to claim some users by adding more functionalities. Business aside, it is amazing to see how the security in Whatsapp is nonexistent. In an attempt to be moderate, I will simply say that using the word “security” is a misinformed statement. Being aggressive, I would use other words.

Charlas a través de Google Hangout

Nov 18, 2012

No hace mucho tiempo, han surgido plataformas de educación online como Coursera y Udacity, que ofrecen cursos de universidades de primer nivel como MIT o Stanford. La posibilidad de acceder a información que hace tiempo se antojaba elitista tiene el potencial de transformar el sistema educativo tal y como lo conocemos, ofreciendo la posibilidad de acceder a estos cursos de manera online, gratuita y permitiendo que los usuarios se encuentren en cualquier lugar del globo. Para más información, recomiendo ver la charla de Daphne Koller, profesora del laboratorio de Inteligencia Artificial de Stanford.

Charla de JUnit y testing en Android

Sep 3, 2012

Aunque finalmente el hangout de la charla no se podrá subir a Youtube, he colgado las diapositivas que usé para la misma. Pueden descargarse desde el siguiente enlace. Para cualquier consulta, puedes contactarme en mi correo personal.

How to (honourlessly) win in Angry Words

Aug 1, 2012

In my scarce free time I usually play Angry Words. For those who have never heard about it (quite unlikely if you’’re reading this article) Angry Words is basically a Scrabble that can be played online against different opponents. There are currently versions for Android and iPhone. Recently, in May 2011, a security hole was reported in WhatsApp which left user accounts open for hijacking. Since May 2011 it has been reported that communications made by WhatsApp are not encrypted, and data is sent and received in plaintext, meaning messages can easily be read if packet traces are available. Together with the well-known storage of the full set of messages sent and received within the application (that can be easily cracked) led me to think if that was a concrete, disastrous development, or a generalized trend in most mobile applications. Therefore, I decided to see if it could be possible to do the same with Angry Words.

Nokia developer program

May 24, 2012

Last March, I enrolled in the Windows Phone Developer Program. At the past MWC in Barcelona, I met a representative of Nokia who informed me about the program. In exchange for 2 applications for WPhone developed within 3 months, developers will get a Nokia Lumia 800. Not bad :-). After successfully applying for the program, I finally published some applications for Windows Phone. These are my series of Intense Languages: Intense Esperanto, Intense German, Intense Dutch, Intense Spanish, Intense Chinese and Intense Latin.

A high-entropy randomness generator

Mar 24, 2012

This cartoon of Dilbert has always fascinated me. You can never be sure about randomness, since the concept of randomness itself provides uncertainty to the process. A few years ago, I even wrote a post on how to achieve randomness using deterministic methods. Nowadays, entropy can always be improved to obtain a more accurate (in this case, it would be more appropriate to say “less accurate” instead) result. This can lead to many philosophical discussions, which are not my purpose.

Flirting with sentimental analysis: my own approach and some case-scenario applications

Mar 18, 2012

Lately I have been interested in applying data analysis to information sources, particularly Twitter. Twitter has all the necessary features to provide an effective real-time analysis: the API it provides allows us to access all the required features for analysis, and the volume of information is just huge. I strongly believe that Twitter has already changed the way to perform intelligent analytics, since it just contains millions of thematic tweets that can be accessed with no limitation.

How intelligent should the AI be

Feb 14, 2012

Reading and thinking the last days about how to implement an intelligent system to play Starcraft, I had time to think about the implications of considering a system “intelligent”. Nowadays, we can develop systems that are able to defeat human intelligence in certain genres. Some board games like chess, or most of the shooters are composed of a limited set of rules, that can be easily modeled and represented with different combinations of techniques (an expert system, considering most of the rules for almost all the situations, is a typical choice). As my colleague Bruno points out (Spanish link), we even have to limit the intelligence of those systems by applying “stupidifying” techniques. In one of the examples Bruno provides, we only allow the AI to attack the human player after spotting him; leading to very weird situations like the one exposed in the following video

How to use the Twitter API to post from Android

Jan 25, 2012

Posting from Android to Twitter is one of the earliest stages for an Android developer. To keep full control over the posting process, we will primarily prefer a pure OAuth post instead of dealing with Intents, so we can keep full control. So as users, we could just think and conclude: the most typical way to authenticate is to pop up a window where we can identify with our username and password to give the application access to our account (not the full account though, just to post from the application!) and forget about the rest of the process. This might be a tricky process for newbies in Android. And of course, Twitter will eventually change its API or registration method, so we will sometimes find that our old implementation is not working anymore.

Push: Client (Android based) and server

Jan 6, 2012

As part of the training and pushing the boundaries in my department, we recently experimented with Push technologies and their application to mobile development. Whereas iPhone seems to support natively push messaging, we soon realized that Android was not perfect in this direction. Surprisingly, they haven’t yet considered that native push support is a technology worth embedding within their official SDK, and this is a complete setback for developers aiming to develop and create their own ideas.

New automatic language translation tool for Android

Dec 26, 2011

Since I have been working in Barcelona, I got so much more in touch with Android and mobile developers than in Germany, since my work there was a little bit more theoretical rather than applied. Although I don’t use on a regular basis Google Translate or any engine to translate my applications (this is a problem of quality vs. quantity, where I bet quality should prevail), I realized that many developers of successful applications are using Google Translate to generate new string files of their projects. And it is, in fact, much more widespread than what I thought. When I have been talking with those developers, they confess after one or two beers that they use web powered engines (i.e., Google Translate) and they usually don’t perform a peer check or a professional review of their generated tokens. Without judging this behavior, I was interested in the procedure, and the first question to arise was: have you automated the process? The most recurrent answer was a “No”, while they began to stare at the floor.

First session of idkLabs

Nov 18, 2011

Last Wednesday we inaugurated the IdkLabs at our office. The underlying philosophy is to create a space of coworking and to put into practice our own ideas and personal projects. It is a real injection of fresh air to work in more creative topics, and to forget a bit of the mechanical, less pleasant development. Plus the result of working in a fun, fresh environment with talented people can only result in good ideas’ conceptions.

cvBlob library for Android

Oct 9, 2011

I recently moved to Barcelona to start working here. Although I’m not working in any computer-vision based project, I still keep a high interest in this field, trying to conduct as many personal projects as possible. My work team is highly motivated and full of professionals, and we all keep our personal projects alongside our work. Recently I met Fegabe in Barcelona, who’s a member of the GTUG Barcelona core team and an Android Developer. We decided to start a Sudoku Solver together for Android. Although there are already many of them published on the Market, we just wanted to do it for fun and to get a bit deeper into computer vision and pattern recognition. There is an OpenCV port for Android, but we decided to keep our implementation pure Java.

Using PHP on server side to generate JSON

Jul 30, 2011

Recently, I published one application into the Android Market that tries to predict when Spain will default. The application uses the data provided by my colleague Juan Carlos Barba from his server. There is basically a set of levels pointing out the seriousness of the Spanish level of CDS and Spread on the debt. The model establishes 5 different levels of alert (or what he called them, DefCon). My implementation customized the data for visualization on the Android Platform.

Why Android still sells less than Apple?

Jul 29, 2011

As an Android developer, I have been concerned during the last months about why the Android Market seems to be less profitable than the App Store. I have access to some statistics of my application's ports to iPhone/iPad: while the free applications don't seem to be affected, the paid applications have a huge gap with their iOS counterpart: they are downloaded up to 50 times more. I can only feel that I chose the wrong mobile platform to develop for. But why is this happening? There are a bunch of well-known differences between the nature of iOS and Android applications, but not all of them affect sales. According to the report of Gartner (April 2011), 38.5% of the smartphone market belongs to Android, while 19.4% belongs to iPhone. It is almost double for Android, and the growth has been astonishing: from an estimated 3.9% in 2009, it has rapidly overtaken all of its competitors

Language Assistant program for Android

May 24, 2011

For a long time, I used to manage the different language files in Android manually. This is an incredibly boring task when our program is growing and getting more complex, since the only way to compare tokens is doing it one by one, and it is an error-prone task. This program is an extension to a similar program developed by my colleague Eugenio Marchiori at the e-UCM group. The program compares all the tokens between two different languages, assigning different codes depending on whether the token is missing in one language, or it has been created. The task of creating new language files is also very easy, since they can be created using a full version as reference.

New Intense Languages versions

May 8, 2011

Some time ago, I released my application Intense Esperanto. The learning method used in I EO has been proposed by Chuck Smith and Judith Meyer, and I developed the application in collaboration with them. Well, now I’m releasing more versions for more languages: this time, Intense German and Intense Latin. Those last versions are not free, but I guess the price is fair: it gives me some extra-money to continue developing more applications, while Intense Esperanto and the other applications remain free.

First application published in the Android Market

Jan 13, 2011

Recently I talked about my last personal project, Farver. After considering if it would be possible to get something more from the effort and hours invested in it, I decided to port the application to the Android Market. The application can be searched for using the word “Farver” in the Android Market. I have also created a video showing both the web and Android applications.

TrafficVision

Dec 18, 2010

TrafficVision is an application presented in the context of AbreDatos (the Spanish Version of Apps for America). With the popularization of traffic cameras on our roads and the improvement of computer vision techniques, new possibilities for improving traffic management are arising. trafiCVision attempts to demonstrate this concept by joining these two worlds. So we’ve developed a platform where camera images of traffic from the Dirección General de Tráfico (National Traffic Department) scattered throughout the Spanish territory are converted into numeric information displaying the number of vehicles each processed image contains. Thus, an interactive map is generated which graphically reflects the traffic congestion in the area where the camera is located. This map provides information in a way that would not be possible just by visiting the image.

Farver, a world color analyzer

Dec 18, 2010

Farver (the Danish word for “colors”) is a program that calculates the average color for a certain concept or word. It has been developed by Enrique López Mañas, although the original idea is from Douwe Osinga. He first developed a desktop-based application, and some time ago I wanted to develop a web-based application (but he was faster and developed another web application). It uses the Google Image Search API and PHP as a primary language. The source code can be downloaded from here. The application can be accessed here

Seminario sobre agentes inteligentes - ADL & STRIPS

Nov 25, 2010

El semestre pasado, como parte del programa de Máster que realizo en estos momentos en la universidad alemana de Aquisgrán, participé en un seminario sobre Agentes Inteligentes. El concepto de seminario es muy diferente del que se encuentra en las universidades españolas: se trata de un curso de participación obligatoria (al menos uno mientras se cursa el máster) sin ninguna clase o encuentro obligatorio. En su lugar, los alumnos tienen que prepararse por su cuenta un tópico, redactar un paper sobre el estado del arte y realizar una exposición pública junto al resto de participantes del seminario. En mi caso el tópico elegido fue ADL y STRIPS, dos lenguajes de planificación automática con los que tenía escasa experiencia (tan sólo había visto superficialmente STRIPS en el curso de Inteligencia Artificial en la Universidad Complutense de Madrid). A partir del seminario, me animé a completar las versiones española e inglesa de la Wikipedia sobre ADL

Videojuego Web

Apr 19, 2009

Este año, durante el curso académico y en la asignatura ingeniería del software, he tenido oportunidad de llevar a cabo como coordinador uno de mis proyectos antiguos: un videojuego de estrategia online. Para realizar este proyecto hemos utilizado bastantes conceptos interesantes: utilizamos el framework de trabajo GWT, de Google, que nos simplificó sobremanera la programación (aunque los inicios, como en muchos de estos frameworks, había una curva de aprendizaje muy pronunciada). Ha sido reconfortante aprender a utilizar un producto de Google (ya tuve experiencias en Alemania con Google Android), y realmente esta gente sabe lo que hace. Utilizamos threads de Java y base de datos MySQL para almacenar toda la información, aspecto que tampoco nos resultó trivial.

<e-Adventure> y videojuegos educativos

Feb 11, 2009

En mi trabajo en el grupo e-UCM de la universidad Complutense de Madrid hemos conseguido muchos avances en el desarrollo de la plataforma <e-Adventure>. <e-Adventure> fue un proyecto desarrollado con distintos fines, principalmente orientados al e-Learning y al desarrollo de tecnologías educativas, aunque desde mi punto de vista también es destacable su capacidad como editor de aventuras. Tanto si estás interesado en videojuegos aplicados al mundo educativo como en el desarrollo de videojuegos de manera rápida y sencilla, sin necesitar un especial esfuerzo en la programación, te recomiendo acceder a la página web y probar la última versión. Se incluyen varios juegos de ejemplo, así como una nueva versión actualizada de los manuales. Puedes ponerte en contacto con e-adventure@e-ucm.es si tienes algún tipo de problema o sugerencia al respecto

Ahorcado en PHP y JavaScript

Feb 11, 2009

Profundizando en la tónica de compartir antiguos trabajos, cuelgo aquí uno de los trabajos que realicé recientemente: un juego del ahorcado alternativo que utiliza JavaScript si el navegador soporta scripting, y PHP en caso contrario. El código fuente se puede descargar del siguiente enlace. Se divide en un fichero denominado modulo.php donde almaceno toda la información referente a la lógica del programa. Desde el fichero ahorcado.php se van realizando las llamadas.

Accesibilidad en AJAX

Feb 11, 2009

Realicé para una asignatura en la universidad (Accesibilidad Web) un trabajo de investigación que abordaba el asunto de la accesibilidad en AJAX. Por si alguien de la blogosfera pudiese beneficiarse de él, aquí dejo los enlaces a la aplicación (un ejemplo de calculadora accesible) y el documento que resume las técnicas y el estado del arte en la cuestión. El documento puede descargarse desde el siguiente enlace. La aplicación de ejemplificación puede contemplarse desde el siguiente enlace. El código fuente puede descargarse desde el siguiente enlace.

Resetear valores auto-incrementales

Jan 14, 2009

Cuando usamos BBDD, y mientras optimizamos configuraciones o interfaces de edición es muy común insertar multitud de valores que posteriormente no necesitaremos, o que formarán parte de un contexto de prueba de la aplicación. En el caso de usar valores autoincrementales como claves primarias de la BBDD (práctica muy común) esto tiene como consecuencia que, al borrar estos datos de prueba, quedan saltos entre los valores incrementales poco estéticos y que en ocasiones no reflejan el estado que uno concibe de la BBDD (secuencias de datos que son insertados conforme a una lógica y un orden).

Backup en MySQL

Jan 9, 2009

Tradicionalmente he ejecutado backups en MySQL utilizando únicamente comandos desde consola. Se podía conseguir de una manera sencilla utilizando código SQL. Para hacer los backups bastaba con: BACKUP TABLE example TO `/backups/` Para posteriormente restaurar la copia de seguridad: RESTORE TABLE pedidos FROM `/backups/` Hay que mencionar que con este comando obtenemos una copia de seguridad de los ficheros que integran la BD y no un script SQL, que suele ser más sencillo de usar. Además, este comando sólo funciona con las tablas de tipo MyIsam, lo que deja fuera un porcentaje de tablas no desdeñable.

Editar páginas web desde el Browser

Jul 8, 2008

Vía Microsiervos tomo nota de la siguiente curiosidad. Si tecleas en tu navegador el siguiente comando: javascript:document.body.contentEditable=‘’true’’; document.designMode=‘‘on’’; void 0 Podrás editar el contenido de la página web. En realidad no tiene mucha aplicación práctica, ya que lógicamente la edición es a nivel local y no en el servidor, pero no deja de ser curioso.

¿Qué es Gopher?

Apr 29, 2008

Mucho ha cambiado Internet como hoy lo conocemos en unos años. Los más ancianos del lugar se acordarán de un extenso conjunto de servicios que han ido cayendo en el olvido en favor de la WWW. Gopher, Verónica, Archie, Wais, lugares como USENET, BBS… acrónimos y palabras que a la mayoría les resultan desconocidos. Había un tiempo en el que no estaba claro qué protocolo saldría victorioso en la guerra por difundir la información. En estos tiempos (hará unos 15 años) Gopher se encontraba en la cúspide de la pirámide de Internet.

Generación de números aleatorios

Apr 12, 2008

La generación de números aleatorios con métodos computacionales es una de las técnicas básicas utilizadas en multitud de disciplinas como la criptografía, los videojuegos, la estadística, la simulación… Existen dos métodos de generación de números aleatorios, básicamente: los números pseudo-aleatorios, que generan una secuencia partiendo de un primer número semilla, o los aleatorios, que siguen unos algoritmos de generación más complejos, tomando generalmente datos del contexto informático en el que se generan (tales como posición del puntero, porcentaje de ocupación de la RAM, etc.) para tener suficiente entropía. En este post, trataré sobre los primeros.

Presentaciones de las conferencias OWASP

Apr 7, 2008

Ya están aquí las presentaciones correspondientes al encuentro del capítulo español de la OWASP 2008 en Barcelona: Amenazas e incidentes de seguridad en entornos Web: realidad o ficción, de Raúl Siles. La seguridad multinivel en servidores web. Luis Calero. Herramientas de análisis estático de seguridad del código: estado del arte, de Luis Rodríguez Berzosa. Una de las presentaciones no está disponible, por alguna razón que todavía no conozco. He escrito un email al encargado de la OWASP, para ver si es posible disponer de ella.

Técnicas de ofuscación sencillas para troyanos

Apr 7, 2008

Hola, Recientemente tuve que conectarme a un ordenador desconocido para consultar el correo. El ordenador no provenía de una fuente hostil, pero sí era potencialmente peligroso conectarme allí sin ningún tipo de prevención. Me llevó a pensar cómo podría saltear las típicas técnicas de captación de contraseñas utilizadas por malware o cualquier tipo de software malicioso. Una manera muy típica de capturar las contraseñas es mediante el uso de keyloggers. Un keylogger es un programa que captura todas las pulsaciones de teclado, entre ellas todas las contraseñas que debemos teclear para poder acceder a distintos servicios a través de internet (foros, clientes de mensajería… y hasta otros más sensibles como correo electrónico o bancos). Tras ello, las envían a algún remoto lugar, en el que seguramente no se limiten a hacer un estudio estadístico. Los keyloggers son programas sencillos, que no siempre son detectados por los antivirus y que pueden ser introducidos con mucha facilidad en un ordenador remoto (bajando un “programa de conexión” de una página pornográfica, de warez o similar, a través de redes P2P, por email…). Las vías de ataque son numerosas, y están en continuo cambio y evolución.

Dominios .es gratis

Apr 5, 2008

Si tienes hasta 30 años y nacionalidad española, el plan Jóvenes en Red, impulsado por el Ministerio de Industria, te ofrece un dominio .es gratis y el alojamiento. Este último será ofrecido por algunos de los mejores proveedores de alojamiento nacionales (con una versión light, lógicamente). Como estrategia para relanzar el contenido en castellano (o cualquier otro idioma nacional) en la red no me parece una mala táctica, aunque como todo habrá que esperar a ver los resultados. Una curiosidad es que los dominios más solicitados hasta ahora son todos los que tienen relación con bodas

JRE cannot be found

Apr 1, 2008

Actualicé mi versión de JDK y mi versión de Eclipse todo al mismo tiempo. Intuía ligeramente que podría darme algún problema realizarlo de manera simultánea. Tras la actualización (incluyendo la descarga de todas las actualizaciones del proyecto Calipso, WPA y otros) , quería depurar una aplicación web, así que cambié a la perspectiva J2EE e intenté inicializar Tomcat desde el panel del servidor. Recibí este amistoso mensaje de error: The JRE could not be found. Edit the server and change the JRE location.

Consejos para contraseñas seguras

Mar 29, 2008

Vía Microsiervos, los mejores consejos de Google para mantener una contraseña oculta y segura:

PHP- Sencillo sistema de login y control de sesiones

Mar 18, 2008

He creado un pequeño sistema de login, con control de sesiones, para poder insertar citas mediante una interfaz web en mi base de datos. El sistema es muy básico, pero quizás alguno quiera tener una pequeña referencia al respecto de cómo empezar. Como de costumbre en este mundo de la programación, el único límite es nuestra imaginación, así que el campo de las posibles mejoras aplicables es muy extenso: control del tiempo de login, modelo de factoría para evitar (o permitir) accesos desde múltiples localizaciones, etc.

OWASP Meeting 2008 - Spanish Chapter

Mar 17, 2008

El pasado viernes asistí a las jornadas OWASP 2008 en Barcelona. Aproveché para visitar de nuevo una ciudad encantadora en buena compañía, y disfrutar del clima cálido que en Alemania ocasionalmente se extraña. Seguía desde hacía algún tiempo la actividad de este capítulo, por su relevancia internacional y sus contribuciones al mundo de la seguridad. Publican frecuentemente papers y documentos que abordan temáticas relacionadas principalmente con el ámbito de la seguridad y de la programación segura. En este enlace puedes descargar gratuitamente sus publicaciones, o adquirirlas físicamente a un precio muy competitivo.

e-Adventure

Mar 17, 2008

e-Adventure es un entorno de desarrollo para juegos educativos desarrollado en el grupo e-UCM de la Universidad Complutense de Madrid, en el contexto del desarrollo de juegos educativos y la integración en entornos de aprendizaje. Se puede visitar el sitio oficial en el siguiente enlace. e-Adventure ofrece la posibilidad de desarrollar juegos educativos a golpe de ratón, con una intuitiva interfaz de trabajo y sin grandes requisitos previos. La información se almacena en ficheros .xml que pueden ser editados sin necesidad del editor.

Ataque del frío

Mar 2, 2008

En la universidad aprendemos que la memoria RAM es una memoria no persistente, y que almacena datos hasta que el ordenador es reiniciado (hasta que el módulo de memoria deja de recibir una corriente eléctrica). Esto es así, pero ¿hasta qué punto? Un equipo de Princeton ha conseguido acceder a la memoria RAM del ordenador, una vez que el equipo ha sido apagado. Los datos permanecen en memoria residual desde algunos segundos hasta el minuto. A nivel físico, congelando la memoria con algún spray anticongelante o incluso con nitrógeno líquido, podemos añadir varios ceros a este orden de tiempo.

Creación de Videojuegos Educativos

Feb 28, 2008

Si estudias en la Complutense estás de suerte. La Facultad de Informática de la UCM ofrece a todos sus alumnos la Acción Formativa “Creación de Videojuegos Educativos para Entornos e-Learning”, convalidable por 3 créditos. En ella se analizarán aquellas características de los videojuegos que les confieren valor educativo, se estudiarán las características de los entornos de e-learning actuales y se discutirá el diseño de distintos juegos educativos. Durante el curso se llevará a cabo el desarrollo de diversos juegos para entornos e-learning en grupos de 4 ó 5 alumnos, empleando las tecnologías y herramientas preferidas por cada grupo de trabajo. La evaluación se realizará sobre los juegos implementados.

Wordpress Mobile Edition

Feb 22, 2008

Wordpress Mobile Edition es un plugin para Wordpress que nos permite ofrecer distinto contenido en función del User Agent que realice la petición. Es decir, podremos distinguir entre agentes móviles y no móviles para ofrecer contenido adaptado (evitando cierto tipo de HTML, evitando Javascript, etc). Puedes descargártelo desde aquí. Las instrucciones son sencillas: mueve al directorio /wp-contents/plugins el archivo PHP, y al directorio /wp-contents/themes el directorio. Ahora, sólo es necesario activarlo desde el menú de Plugins, dentro de la configuración del Wordpress, y Voilá!

Cursos gratuitos de Sun

Feb 22, 2008

Si eres estudiante matriculado en la UCM, ahora podrás tener acceso gratuito a los cursos de Sun Learning connection. La mayoría de estos cursos involucran temáticas relacionadas con Solaris y Java. Es necesario aportar estos datos cuando se realiza el registro (company name y company ID): Company Name: SAI-Universidad Complutense de Madrid Company ID: CUS-0000096750 Aquí una pequeña muestra de lo que estos cursos ofrecen. Incluso Sun ofrece certificados por aquellos cursos que se han conseguido finalizar con éxito, como se puede ver en el User Guide (queda por ver, no obstante, cuál es el valor real, o la valoración que puede llegar a tener, un certificado que se descarga y se imprime).

Crear imágenes de Windows XP con Ghost y Sysprep

Feb 19, 2008

Generalmente, tiendo a instalar y reinstalar sistemas operativos con bastante frecuencia. Con mi horario tan infernal, no dispongo del tiempo suficiente para sentarme y reinstalar y configurar hasta el último programa. Aunque es relativamente fácil usar un backup de mi sistema para el trabajo diario, tiendo a cambiar periféricos con bastante frecuencia, y restaurar un sistema del que no se han eliminado ciertos drivers tiende a causar estragos en una nueva configuración. Para hacer este proceso más rápido, he creado una imagen fantasma de mi disco duro después de realizar una instalación básica. Ahora, en lugar de tener que invertir unas cuantas horas para dejar un sistema a punto, puedo hacer eso en 15 minutos con solo 6 clicks de ratón. El truco para esto es utilizar Norton Ghost o cualquier otro software de imagen y Microsoft Sysprep.

Asus EEE

Feb 15, 2008

Hoy he tenido la posibilidad de juguetear con él portátil Asus EEE. Por si a alguien le ha descolocado el nombre, Asus EEE forma parte de una tendencia que surgió a raíz del anuncio de Negroponte de crear portátiles de baja gama, bajo consumo y bajo precio destinado a países en desarrollo (por cierto, que Brasil canceló hace poco tiempo un pedido de varios millones de dólares de estos ordenadores como consecuencia de la subida final del precio hasta 350 $). Estos ordenadores podrían suponer una revolución educativa para todos aquellos países del cono sur, donde entre muchos otros factores, el acceso a la educación se ve imposibilitado por el coste de la misma. No obstante, parece ser que tendrán su cuota de mercado en la mitad norte del planeta… Asus EEE es tan pequeño que para muchas personas rozará lo inutilizable. Tan sólo 7’’, y una resolución máxima de 800x480, nos retrotrae a otras épocas pasadas de la evolución de los monitores. Dispone de una memoria Flash de 4 GB y 512 MB de RAM. Con todo lo que se necesita para ponerse a funcionar (¡hasta una webcam integrada!) y un conector WiFi con especificación .g, desde luego consigue entrar en los propósitos que originalmente Negroponte se planteaba. Para ahorrar en costes de licencias, su sistema operativo es Linux.

Seguridad y privacidad

Feb 4, 2008

Vía Clay Bennet. Y es que ya lo dijo Benjamin Franklin: They who would give up an essential liberty for temporary security, deserve neither liberty nor security.

Navegación anónima

Feb 4, 2008

Muchas veces hemos navegado por Internet con nuestro navegador favorito y sabemos que vamos dejando nuestro rastro allá por donde vamos, o bien queremos opinar en algún foro como una persona distinta, o bien queremos votar más de una vez en alguna votación, mandar un correo electrónico y que no se sepa el origen, etc etc etc. En el otro lado de la balanza, realizar un ataque sobre un objetivo o dejar una dirección IP falsa en un registro es otro de los propósitos

Micrófono y cámara iSight Ubuntu

Jan 30, 2008

Ayer, tras un tiempo sin volver a intentarlo, di por fin con la clave para poder configurar el micrófono y la cámara iSight para Ubuntu en Macintosh. En el mundo de los ordenadores, si tenemos dos soluciones, la que será más correcta y menos problemática será la más sencilla. Pues bien, el problema al que me enfrentaba… era que por defecto, el volumen está al mínimo. Para solucionarlo, basta con irse al control de volumen (doble clic sobre el icono de la barra de tareas), Preferencias, marcamos la casilla Captura y veremos que tenemos una pestaña, Grabando. Basta con subir el volumen :D

Port Knocking

Jan 28, 2008

Quizá esta información sea novedosa para muchos de vosotros. A pesar de no tratarse de un tema novedoso, ya que hay literatura al respecto desde el 2003, quizás sea un concepto desconocido, al menos para la comunidad de habla hispana en internet. Es sabido que la seguridad electrónica nunca puede basarse en una sola medida o nivel de seguridad. Así, hablaremos de sistemas con doble, triple o con niveles más altos de seguridad, según exista una combinación de medidas que ayuden a asegurar y hacer impenetrable un sistema (por ejemplo: a la hora de asegurar un router que provee acceso inalámbrico, un filtro a nivel de MAC + una encriptación WPA a 256 + una elección de direcciones IP no estándares + servidor DHCP deshabilitado constituiría un cuádruple nivel de seguridad).

Summer Camp 2008 Garrotxo

Jan 21, 2008

Call4participation Está oscuro, mis dedos se mueven al ritmo de la música, simplemente la luz del monitor es mi punto de referencia, caracteres y más caracteres aparecen en pocas pulsaciones y mi cerebro agarra la información que necesito. Un delay, escucho y oigo los animales de la noche, miro alrededor y sólo hay calma absoluta, miro hacia arriba y veo las estrellas, las contemplo y pienso en mi insignificancia, tomo una bocanada de aire fresco y lo trago, una sensación de satisfacción recorre mis venas y viene a mi cabeza la imagen de un equivalente mundo virtual donde la omnipresencia es posible, donde el más rico no es el más poderoso, donde después de la desconexión existe la reconexión, donde el medio de transporte es la electricidad y el billete es un terminal.

Emulador MS-Dos para Macintosh

Jan 20, 2008

Tras localizar la descarga de unas cuantas ROMs con las que disfruté a temprana edad, he podido localizar para Macintosh una herramienta de simulación bastante correcta, DosBox. Dispone de versiones para los 3 SO. La página oficial es esta, y la instalación para cualquier plataforma dista de ser complicada. Como curiosidad con un componente añadido de melancolía, me gustaría colocar una captura de pantalla de un par de los juegos a los que dediqué más tiempo durante mi temprana infancia, y que a la postre marcaron mi tendencia de entretenimiento electrónico. Ishar III, Messengers of Doom y Transarctica.

Vivir del OpenSource

Jan 13, 2008

Una discusión que más de un defensor del software libre y las licencias libres habrá tenido es si se puede vivir de un producto que se libera al mercado bajo GNU, Copyleft, etc. Multitud de siglas y extranjerismos que promulgan valores ciertamente altruistas, pero que no pueden evitar que nos hagamos una pregunta en un mundo dominado por el capitalismo y el libre mercado: ¿y yo qué gano? La licencia GPL dice claramente que podemos obtener beneficio con un software liberado de esta manera (echa un vistazo aquí si no estás familiarizado con la filosofía OpenSource). En realidad, esta licencia se centra en dejar claro que podemos copiar y modificar un programa GPL sin necesidad de permiso expreso por parte del autor (pues la propia licencia lo especifica) y deberemos tener acceso al código fuente del mismo. Es decir, las entrañas del software, el conjunto de algoritmos y métodos que utiliza para resolver problemas.

Instalación mínima de Ubuntu

Dec 20, 2007

Un principio básico de seguridad nos dice que hemos de mantener únicamente la cantidad de software indispensable en un sistema operativo con funciones de servidor para hacerlo funcionar. Cualquier aplicación adicional que instalemos, y que no sea realmente necesaria, puede comprometer a nuestro equipo seriamente. Aplicaciones ofimáticas, juegos, navegadores… presentan bugs explotables tales como desbordamientos de buffer, ataques de flood, apertura de puertos… que pueden representar un vector de ataque en el futuro.

Configurar accesos directos en Linux

Dec 14, 2007

Una aplicación interesante en Linux es aquella que nos permite lanzar una consola con tan sólo presionar una tecla, un navegador, el cliente de correo… pero no sólo eso, también nos permite ejecutar comandos más específicos (montar una imagen o unidad virtual, activar la tarjeta WiFi con ndiswrapper, etc). En realidad es bastante sencillo. En mi Macintosh buscaba una aplicación que darle a mi tecla manzanita, tan útil en mi Leopard, tan poco útil en mi Ubuntu. Decidí asignarle la consola, para no tener que llevar el botón del puntero continuamente hasta el acceso directo. Para ello, basta seguir los siguientes pasos:

Cedega

Dec 13, 2007

El principal motivo que desde siempre ha atemorizado a posibles usuarios switchers (usuarios migrados de un sistema operativo a otro, y generalmente con origen en sistemas Microsoft) ha sido la falta de portabilidad de sus aplicaciones, y entre estas aplicaciones el género de entretenimiento electrónico tiene una buena parte de culpa. En los últimos años, paquetes de aplicaciones estándar han sido portados con mayor o menor éxito hacia Mac, Linux, FreeBSD, tales como aplicaciones de ofimática, diseño gráfico, diseño web… Muchos portales se dedican a recopilar información sobre las equivalencias entre Linux y Windows a nivel de aplicación y funcionalidad, o entre Windows y Mac.

Problemas que no son problemas

Dec 11, 2007

Hay ocasiones en las que, en mundos que se supone que existe una mayor profesionalidad que en las revistas del corazón, el comportamiento tiende al periodismo amarillo y la extensión de bulos para ganar unas cuotas de audiencia. Un ejemplo de esto se puede encontrar en la última inyección SQL publicada en Security Vuln, que afectaba a nuestro querido CMS Wordpress. En realidad mi intención era comprobar esta vulnerabilidad, sobre todo de cara a actualizar (o desactualizar) mi CMS para evitar ataques de 0 day que dieran al traste con mi trabajo de los últimos días. Sin embargo, mi gozo en un pozo cuando veo que esta inyección SQL no surte el más mínimo efecto:

Tag der informatik

Dec 11, 2007

El pasado viernes tuve la oportunidad de presentar en el Tag der informatik celebrado en la RWTH el proyecto en el cual me encuentro trabajando. Virtual Campfire. Mi responsabilidad en el mismo abarca dos áreas: la integración de la aplicación dentro de una red inalámbrica mallada, y portar una aplicación para PDA escrita en C# a una versión web-based, posiblemente escrita en PHP (me encuentro ahora mismo escribiendo el documento preliminar para el proyecto)

Migración de escritorios Windows a Linux

Dec 11, 2007

Acabo de leer este interesante artículo publicado en Kriptópolis. En él se ponen cifras y se dan datos de una pregunta que más de una vez nos habremos planteado. ¿Cuál es el coste real de migrar un sistema operativo propietario a Linux? Las cifras que se dan son las siguientes: migrar 300 estaciones Windows a Linux cuesta 13.200 dólares, lo que al cambio saldría a unos… ¡35 euros por estación!. Además, la migración da derecho a:

De como configurar Ubuntu 7.10 Feisty en Macbook

Dec 10, 2007

Tras un tiempo buscando información, en ocasiones dispersa, he conseguido configurarlo para la mayor parte de las funcionalidades que utilizo con frecuencia. El Macbook que poseo es el previo al modelo actual, el cual fue liberado por Apple el mes pasado. En concreto es el modelo intermedio, con 100 GB de disco duro, 1 GB de RAM y un procesador Intel Core 2 Duo a 2.16 GHz. La tarjeta de red inalámbrica posee un chipset Atheros en los nuevos modelos. Este chipset nos proporciona multitud de ventajas para trabajar con nuestra tarjeta y realizar algunas tareas específicas. Dado que cualquier visitante puede encontrar útil la ayuda para la configuración del Macbook, he aquí una pequeña guía al respecto:

IPTables para Windows

Dec 3, 2007

Trabajo con los tres sistemas operativos mayoritarios del mercado en mayor o menor cuantía, y en función de la necesidad específica que requiera (en mi trabajo como HiWi en la universidad me desenvuelvo prácticamente con Linux, para usar muchas aplicaciones de programación o de diseño comerciales utilizo Windows en su versión XP, Macintosh principalmente con propósitos domésticos…) Desde hace un tiempo me rondaba la cabeza encontrar un firewall específico para Windows que tuviese las características de IPTables para Linux. Con el tiempo, y evaluando varias alternativas, he conseguido llegar a WIPFW . WIPFW es un firewall software para plataformas Windows basado en IPFW1, un firewall bastante popular para la familia BSD.

Apertura

Dec 3, 2007

Tras un periodo de peleas y ajustes en el diseño del sitio, inauguro el blog con intenciones y deseos pre-navideños que espero que acaben llegando a buen puerto. Saludos.

HTTP chunk requests with Android and ktor

Planted May 23, 2023
Pruned June 9, 2025

HTTP chunk requests with Android and ktor

In this very short article, I will explain briefly what is a chunk or streamed HTTP request, what are the benefits of using it, and how it works in Android.

Android apps use HTTP requests to download data from a backend. This information is stored and processed on the app to make it functional.

HTTP requests are executed using different frameworks on Android. The most common ones are Retrofit or OkHttp.

Simplifying the underlying network operations, and after identifying the IP address of the computer hosting the requested URL, an HTTP request looks like follows:

OkHttpClient: --> GET https://api.yourserver.com/sandbox/v1/example/23aa13d2-b161-432d-a67e-c50e8783f7dd http/1.1
OkHttpClient: X-apikey: AATR1oqYAZzp6o6ndALfIk6GG1dOcDED
OkHttpClient: Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRw...
OkHttpClient: Accept-Language: en-US
OkHttpClient: Connection: close
OkHttpClient: Accept: application/json
OkHttpClient: Accept-Charset: UTF-8
OkHttpClient: User-Agent: Ktor client
OkHttpClient: Host: api.yourserver.com
OkHttpClient: Accept-Encoding: gzip
OkHttpClient: --> END GET

The HTTP request contains (among others) the following fields:

  • The HTTP method used: GET, POST, PUT, PATCH or DELETE. There are actually 8 different HTTP methods, being the remaining ones CONNECT, OPTIONS and TRACE.
  • Authorization headers (things like an API Key, or the Auth key we will need to identify ourselves as lefit clients).
  • Metadata headers for encoding, language, charsets, content type, etc.

The full specification of the HTTP 1.1 protocol can be found in the RFC 2616, whereas the HTTP 1.0 specification can be found in the RFC 1945.

In a world where multiple SDKs provide us with an abstraction layer and simplify those operations, RFCs might not be needed to check often. Android developers, for instance, can benefit from the usage of multiple frameworks (Retrofit, OkHttp, Ktor, etc…) that provide already all of the required implementations. This was not always like that: in previous times, it was necessary to check RFCs with certain frequency, since feature-complete SDKs where not always available on each stack.

Executing standard HTTP requests works at a high level as follows:

image

When the backend has processed the request, it returns it at once to the client. This works for most cases, but there are cases where we want to optimize further.

Imagine an endpoint that contains a complex logic that eventually takes more time until the full data is ready. Or maybe the endpoint relies on further subqueries to prepare the entire data, which will take some time until it is ready. In this case, it might be worth considering a Chunk (or streamed) request.

HTTP Streaming is a data transfer technique that allows a backend to continuously send chunks of data to a client over a single HTTP connection that remains open indefinitely (or until the data has been processed). A request like this can be of advantage to allow a client to dispose immediately of certain data, while the backend processes the rest.

This might remind the reader of using Sockets. HTTP and Sockets work similarly, although there are a few differences between them.

  • Websockets are event-driven, whereas HTTP is not. Generally, the best choice for real-time communication is sockets, since they have a lesser overhead to initialize and maintain a connection.
  • Sockets are a full-duplex asynchronous messaging mechanism. Both client and server can exchange messages independently.

There are also a few more differences in how they operate at the network level. This falls out of the scope of this article, but if you are interested you can read the Wikipedia article that explains the OSI model.

However, there might be cases where it is more convenient to use an HTTP Streamed request. From infrastructure to reusing certain models already being handled by the HTTP client, the casuistic can be wide.

Ktor supports this relatively out-of-the-box. The following snippet is able to execute a streamed request from a given API:

fun main() {
    val client = HttpClient(CIO)
    val file = File.createTempFile("files", "index")


    runBlocking {
        client.prepareGet("https://api.example.com").execute { httpResponse ->
            val channel: ByteReadChannel = httpResponse.body()
            while (!channel.isClosedForRead) {
                val packet = channel.readRemaining(DEFAULT_BUFFER_SIZE.toLong())
                while (!packet.isEmpty) {
                    val bytes = packet.readBytes()
                    file.appendBytes(bytes)
                    println("Received ${file.length()} bytes from ${httpResponse.contentLength()}")
                }
            }
            println("A file saved to ${file.path}")
        }
    }
}

To verify that this is working, you can execute a cURL against the streaming API, using a command similar to the one below:

curl --location --request GET 'https://api.example.com' --header 'X-apikey: yourAPIkey' --raw

When you execute this, there is an interesting twist in the story. You will be able to see the response from the backend as you normally see it, but this time each chunk will be separated by a number, specifying the size of the next chunk:

image

As promised, this is not the longest article I’ve written, but I hope it provides some context on Streamed requests, and how they work — and eventually, you can get some inspiration to apply when for your project, in case you need them.

I write my thoughts about Software Engineering and life in general on my Twitter account. If you have liked this article or if it did help you, feel free to share, 👏 it and/or leave a comment. This is the currency that fuels amateur writers.