DroidCon Poland: Is your app really connected?

2017-12-02 Android, Conferences No comments

Yesterday, I gave a presentation about connectivity in the Android apps during the DroidCon Poland 2017 Conference in Kraków.

Below, you can see slides from this presentation.

There’s also tweet related to this presentation from DroidCon Kraków:

I hope, you enjoyed it. Any kind of feedback is welcome (in the comments below this article or via e-mail).

Don’t forget to check ReactiveNetwork library I mentioned during the presentation.

Simple reactive HTTP client & server with RxJava, Vert.x and Android

2017-11-09 Android, Java, RxJava, Vert.x No comments

During Hack Your Career event at the Silesian University of Technology, I’ve prepared a presentation titled Reactive Programming – Efficient Server Applications with a colleague from work. Arek told about theory of Reactive Programming, shown basic concepts, data types and a few examples in the code. During my part of the presentation, I’ve wrote a very simple server and client in Java (9 on the server, 7 on the client) with Vert.x (Core and Rx), RxJava 2, OkHttp 3, Android and RxAndroid. Presentation was targeted mainly to the university students with no experience with reactive programming, but it was an open event and anyone could attend it.

Below, we can see a very simple code snippet showing how to create a reactive HTTP server with Vert.x. We can create a stream of requests, make Flowable out of it, apply any kind of RxJava 2 operator including backpressure handling and subscribe the stream. Moreover, we can also reactively start the server with rxListen(int port) method. This is just a basic example, where will be sending request to the only one endpoint. In the case, when we want to handle more endpoints, we can use vertx-web library and design REST API.

final HttpServer server = Vertx
    .vertx()
    .createHttpServer();

server
    .requestStream()
    .toFlowable()
    .onBackpressureDrop()
    .subscribe(request -> {
      logger.info("{} {}", request.rawMethod(), request.absoluteURI());
      request.response().end("request received");
    });

server
    .rxListen(8080)
    .subscribe(httpServer -> logger.info("server is running at port 8080..."));

We can build this server with Gradle as follows:

./gradlew shadowJar

and then, we can run it:

java -jar build/libs/server-fat.jar

Our client will be an Android application, which will read data from the accelerometer sensor, send it to the server and display it in the TextView on a mobile device. We will use ReactiveSensors library (which was recently migrated to RxJava 2) for getting sensor readings as a Flowable data stream. Next, we will apply backpressure DROP strategy, filter only events of changing sensors (we neglect changing of the accuracy), read only one event per one second with throttleLast(int, TimeUnit) operator and map event to a String with device coordinates. Next, we are ready to send data with Completable performRequest(String), which we created earlier. Sensors readings are acquired in the computation() scheduler, send to the server with io() scheduler and passed to the UI thread on Android with AndroidSchedulers.mainThread(). Distributing operations to the different schedulers is made with subscribeOn(Scheduler) and observeOn(Scheduler).

reactiveSensors
    .observeSensor(Sensor.TYPE_ACCELEROMETER)
    .onBackpressureDrop()
    .filter(ReactiveSensorFilter.filterSensorChanged())
    .throttleLast(1, TimeUnit.SECONDS)
    .map(this::getSensorReading)
    .doOnNext(event -> performRequest(event)
        .subscribeOn(Schedulers.io())
        .subscribe())
    .subscribeOn(Schedulers.computation())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(event -> tvReadings.setText(event));

It’s worth noticing that Completable performRequest(String) is using OkHttp 3 under the hood as a HTTP client, because it’s very simple example with one endpoint. In the case, we want to handle more endpoints on the client-side, it’s better to use Retrofit library.

It’s also interesting that in our case, we can simulate behavior of the accelerometer and other sensors with the latest Android device emulator available in the Android SDK. It works surprisingly smooth.

Complete working example can be found at: https://github.com/pwittchen/reactive-client-server.

Later, I’ve also shown, how to use RxJava to distribute computational operations to a different threads of the CPU cores, but I’ll probably publish a separate article about that on this blog. It was the same example I shown during my JDD presentation this year.

Slides from my part of the presentation are available below.

5 ways to attend expensive IT conferences for (almost) free

2017-11-02 Conferences No comments

Introduction

In the past months, I’ve attended a few conferences and meetups related to IT. I also plan to attend a few more in the last quarter of the year as a speaker. I’d like to show you a few tips, which can encourage you to attend such events, be more involved in them and spend some time away from your desk ;-). If you are working in a software company, in the most cases you could treat going for a conference as a non-customer facing business trip, so your regular days off will be safe and can be used for your personal plans and holidays :-).
I tried all of the methods described in this article both in Poland and abroad, so I can tell you they’re confirmed in practice.

Use your company’s educational budget

There are companies, which offer so called educational budget, which is defined each year. Such budget can be used for attending the conferences and trainings. In the company where I work now (SAP Hybris), I have such benefit and I could use it to go to the Spring I/O in the Barcelona, Spain last year, J On The Beach in Malaga, Spain and Devoxx in Kraków, Poland this year. Of course, travel, food and accommodation expanses were covered by this budget as well as conference tickets.


ICE Kraków Congress Centre – Devoxx Poland 2017 Venue


Malaga, Spain

Be a speaker

This year I was a speaker during JDD conference in Kraków, Poland. I had confirmed business trip and an accommodation in high quality hotel paid by the conference organizers. I could also attend a dinner with other conference speakers and see all conference talks and hang out with participants without spending a penny. In the December 2017, I’m also going to be a speaker during DroidCon Poland conference, where organizers offered to cover accommodation costs as well. Usually, you can expect that from good quality events, but it may happen that part of the costs will have to be covered by you, so it’s good to be prepared for that.


My JDD 2017 Conference Talk in Kraków, Poland

Be a rejected speaker

I’ve send my submission during Call For Papers for GDG Dev Fest in Lviv, Ukraine. I was rejected, but organizers offered me a free conference ticket. Organizers had over 150 C4P submissions including those of people from Google, Twitter, etc., so I wasn’t lucky this time. Ukraine is quite cheap country comparing to Poland and I wanted to visit Lviv, so I paid for travel and accommodation by myself and joined this event.


GDG Dev Fest Ukraine 2017 Conference in Lviv


View from Pravda Beer Theatre on the Market Square in Lviv, Ukraine

Be a blogger

I create this blog for a few years and I think its quality is becoming better and better every year and more people visit it. Last year, JDD conference organizers offered me a free conference ticket in exchange for promoting their conference on my blog. It was good exchange, because this event is interesting and related to the content of my website. In addition, conference ticket is not so cheap and costs about ~500 PLN or something like that. This situation encouraged me to be more engaged in the Java community and this year I attended the same conference as a speaker.

Be a volunteer

From a long time I wanted to visit London in UK and attend DroidCon London conference as well. It’s one of the most popular Android conferences in the Europe. Conference ticket is very expansive and costs 695 GBP, which is approximately ~3352 PLN. Nevertheless, you can save some money if you buy it very early (like almost one year before the conference). I used most of my personal educational budget in the company and I could, but I didn’t want to spend such amount of money from my own pocket just for a conference ticket. I’ve sent to the organizers a proposal of promotion of their event on my blog in exchange for a free conference ticket. They didn’t really want that, but they asked me to be a volunteer for a 2 days, so I could help them a little and get the free ticket. I decided to go for it. UK is much more expansive place than any city in Poland, so I had to spend some money for accommodation, food and transportation. Nevertheless, I don’t regret it, because it was nice experience and London is worth visiting at least for a few days. Moreover, I haven’t really encountered typical London weather. There was hot and sunny during my stay. Only one day was a bit cloudy with a small rain, but it wasn’t as cold as in Poland on my way back. I also made a few connections and gave my business cards to a few people. Such kind of networking can create new possibilities related to work, local & global communities, speaking on meetups, conferences etc. Of course, when you go to UK, don’t forget to check out the map of every pub in UK.


Business Design Centre London – DroidCon London 2017 Venue


London, UK in late October 2017 (The Shard is visible in the background)


Tower Bridge visible from The Shard, London, UK

Summary

As you can see, there are many ways to attend expensive IT conferences and you don’t really have to spend your own money on the tickets every time. You just need to be in a good company, a bit more engaged, give something from yourself to others and it will bring you profits. Attending many conferences won’t make you the best developer in the world, but sitting in front of your desk and doing the same thing for many days won’t do that either. It’s good to find a balance and time for the new experiences, changing your surroundings for some time, seeing new places and meeting new people. When you can mix that with your profession and work, that’s great!

Meet & Code 2017: “Git – tips & tricks” presentation

2017-10-21 Conferences, Git No comments

Recently, during Meet & Code event organized by Media 3.0 and SAP Hybris, I’ve gave a talk for university and high-school students about basics of Git. Presentation was titled Git – tips & tricks and was organized at the Silesian Univeristy of Technology in the AEI Department where I was studying a few years ago. Presentation covered quite essential usage of Git, which could be helpful for people who are planning to learn it from the scratch. Nevertheless, in the talk I included a few tips, which could be applied even by more advanced users in their daily work. You can view slides from this presentation below.

JDD 2017: Get ready for java.util.concurrent.Flow! – slides, code and recap

2017-10-05 Conferences, Java, RxJava 2 comments

Recently on the JDD 2017 conference, I gave a presentation regarding introduction to Reactive Streams standard in Java 9. I also talked about existing implementations of this standard with the strongest focus on RxJava2 and created simple Reactive Streams implementation in pure Java 9 during the presentation. Below, you can find slides from this talk.

Code snippets shown during this presentation are available at https://github.com/pwittchen/java-flow-experiments.
I have done a tiny live coding session during this talk. Luckily, everything went fine, the code was compiled and executed without errors. Everything I’ve done during this presentation and additional exploratory unit tests could be found in this repository so you can check it out if you’re interested.

There were also tweets made by the audience just before the presentation.

I can say that conference room was full. There were even people sitting on the floor due to lack of free chairs what really surprised me. In the Eventory app, more than 85 people joined the lecture, but in reality, there could be about 100 people or more. It was really flattering that such huge and great audience decided to listen to my talk. In fact, that was the biggest audience I have ever had during the public presentation so far. Moreover, people were asking many interesting questions during Q&A session and after the presentation, so it means they were interested in this topic and they wanted to learn more, understand it and apply it in their projects. If you haven’t had the opportunity to see this presentation, but you would like to, JDD organizers will provide video recordings from the sessions. In addition, you can monitor Talks page on this blog, where I publish my past and upcoming sessions. Probably, I’ll present this topic again during one or two meetups because people are interested in it.

Joining JDD 2017 as a speaker was a great experience. It cost me an additional work and effort after hours, but at the end of the day, it was totally worth it and it was much easier to establish contacts and meet new people as a speaker than as an attendee, what is important for me. Moreover, I could learn new things from other people as well because general level of the conference presentations was pretty high.

Thanks for the interesting questions, discussions, other good presentations and support before the talk!

Below you can find two pictures from this talk made by JDD 2017 photographers.

JDD 2017: Get ready for java.util.concurrent.Flow!

2017-10-02 Conferences, Java, Po polsku, RxJava No comments

Get ready for java.util.concurrent.Flow!

On the 3rd of October 2017 I will be giving a talk titled “Get ready for java.util.concurrent.Flow! at JDD 2017 Conference in beautiful Kraków, Poland.
The talk will be in Polish and you can find a short Polish description of it below.


W Javie 9 otrzymamy do dyspozycji nową klasę z pakietu java.util.concurrent o nazwie Flow. Idea stojąca za tym rozwiązaniem wywodzi się z projektu Reactive Streams. W związku z tym, najnowsza wersja Javy będzie posiadała natywne wsparcie dla tworzenia reaktywnych aplikacji zgodnych ze wspomnianym standardem. Już dziś możemy z tego standardu korzystać i warto się z nim zapoznać wcześniej. Co więcej, od jakiegoś czasu mamy do dyspozycji istniejące implementacje Reactive Streams, które są sprawdzone i gotowe do użycia w projektach na platformę JVM. Wszystkie biblioteki implementujące ten standard mogą ze sobą współpracować dzięki wspólnemu API. Programowanie reaktywne pozwala na pisanie wydajnych aplikacji, które optymalnie wykorzystują zasoby sprzętowe. To podejście pozwala również na dodanie czytelnej warstwy abstrakcji dla aplikacji wielowątkowych oraz wygodne zarządzanie strumieniem danych bez utraty czytelności kodu. Warto dodać, że programowanie reaktywne sprawdza się zarówno na serwerach obsługujących dużą liczbę żądań, jak i na urządzeniach mobilnych, gdzie większość operacji musi być wykonywanych asynchronicznie bez blokowania głównego wątku. Podczas prezentacji chciałbym przedstawić na przykładach popularne implementacje standardu Reactive Streams w Javie 8 takie jak RxJava2 i Project Reactor oraz przykładową, prostą implementację tego samego standardu w Javie 9 z wykorzystaniem klasy java.util.concurrent.Flow.


Date and time of the talk: Day 1, Track 4, Oct 3rd 3:00pm – 3:45pm

This will my very first talk on the JDD conference. I’ve attended this conference a few times as a participant in the past and now it’s time to give a talk as a speaker. I warmly invite everyone who is going to join JDD this year to attend my talk. I’ll try to do my best to keep you interested. There will be an overview of reactive programming, reactive libraries and reactive streams interfaces in Java 9. To keep you awake, we’ll do some live coding and demos on stage.

Recommendations

Due to the fact, I will be speaking on the JDD for the first time, and I’m participating in JUGmajster competition representing SJUG team with two of my colleagues Daniel Pokusa and Grzegorz Gajos. Check out their talks too!

You should also view complete conference schedule. In addition, don’t forget to visit main page of the conference at https://jdd.org.pl.

If you would like to have a discussion, ask a question or just have a beer together, don’t hesitate to reach me! 🙂

See you in Kraków!

Integrating ErrorProne and NullAway with an Android project

2017-09-15 Android, Gradle, Java, Static Code Analysis No comments

Recently, with the remote help of guys from Uber in California, I integrated NullAway and ErrorProne with the one of my open-source Android projects.

What is NullAway?

Basically, it’s a tool to help eliminate NullPointerExceptions (NPEs) in your Java code. It detects situations where NPE could occur at the compile time.

Let’s have a look at the following code:

static void log(Object x) {
    System.out.println(x.toString());
}
static void foo() {
    log(null);
}

NullAway will find out that we’re passing null and we’ll get appropriate error message:

warning: [NullAway] passing @Nullable parameter 'null' where @NonNull is required
    log(null);
        ^

It’s good to have checks like that because they eliminate possible bugs in advance and follows Clean Code principles.

A few words about ErrorProne

NullAway is built as a plugin to ErrorProne and can run on every single build of our code. Moreover, ErrorProne can perform other checks on our code, which can find out commonly people mistakes. E.g. it can detect a situation, where programmer forgot to add @Test annotation in the unit test method in a test suite and other things. It has built-in bug patterns, which are used during code analysis.

Integration with the Android project

I’ve integrated ErrorProne and NullAway with ReactiveNetwork Android library.

First, in the main build.gradle file, I’ve added the following lines:

ext.deps = [
            ...
            nullaway          : 'com.uber.nullaway:nullaway:0.1.2',
            errorprone        : 'com.google.errorprone:error_prone_core:2.1.1',
            ...
            ]

buildscript {
  repositories {
    jcenter()
    maven {
      url 'https://plugins.gradle.org/m2/'
    }
  }
  dependencies {
    ...
    classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.0.11'
    classpath 'net.ltgt.gradle:gradle-apt-plugin:0.11'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
  }
}

Next, in the library/build.gradle file, I’ve added appropriate plugins in the top:

apply plugin: 'net.ltgt.errorprone'
apply plugin: 'net.ltgt.apt'

Afterwards, I could add dependencies:

dependencies {
  ...

  annotationProcessor deps.nullaway
  errorprone deps.errorprone
}

The last thing to do, is the task responsible for running analysis during project compilation:

tasks.withType(JavaCompile) {
  if (!name.toLowerCase().contains("test")) {
    options.compilerArgs += ["-Xep:NullAway:ERROR", "-XepOpt:NullAway:AnnotatedPackages=com.github.pwittchen.reactivenetwork"]
  }
}

That’s it! Now, I could run analysis by typing:

./gradlew check

and fix the issues.

I think, a quite similar approach and configuration could be applied to a regular, pure Java project built with Gradle.

If you’re interested in the complete configurations, check it out in my project at: https://github.com/pwittchen/ReactiveNetwork.
You can also view Pull Request #226 made by @msridhar (kudos for him!).

Building and running SAP Hybris Commerce Platform via Gradle

2017-09-01 Gradle, Hybris 1 comment

Introduction

I really like Gradle build system for JVM apps. It has flexibility like Ant and great dependency management capabilities like Maven. It addition, it doesn’t use XML notation, but Groovy programming language, so builds configurations are simple, concise, easier to read and easier to create. In my opinion, Gradle is truly modern build system for JVM apps. Nevertheless, there are projects, which are pretty old and use older systems like Ant. For example, all Hybris projects are based on Ant. Moreover, they have their custom setup and configurations, internal extensions system, etc. I was wondering if it’s possible to migrate Hybris Platform build from Ant to Gradle. That’s why I created a simple Proof of Concept.

Migrating from Ant to Gradle

If we want to use Gradle, we need to install it first.

sudo apt-get install gradle         # if we're on Ubuntu Linux
brew install gradle                 # if we're on macOS

For more details and instructions for other systems, check official Gradle installation guide.

Then, we need to go to our Hybris platform directory and navigate to hybris/bin/platform

After that, we need to initialize gradle inside this directory by running gradle command.
Next, we need to create gradle wrapper by running gradle wrapper command.
Now we should have the following elements in our directory:

  • .gradle (directory)
  • graldew (wrapper file for Unix)
  • gradlew.bat (wrapper file for Windows)

Afterwards, we can create build.gradle configuration file.

It should have the following contents:

ant.importBuild 'build.xml'
apply plugin: 'java'

repositories {
  jcenter()
}

task run() {
  doLast {
     exec {
          executable "./hybrisserver.sh"
      }
  }
}

task cleanGeneratedDirs(type: Delete) {
  delete "../../data"
  delete "../../log"
  delete "../../roles"
  delete "../../temp"
}

task cleanConfig(type: Delete) {
  delete "../../config"
}

dependencies {
  compile fileTree(dir: 'lib', include: ['*.jar'])
}

Now, we can execute the following command:

./gradlew clean build

and platform will be built.

In order to initialize the platform, we can call:

./gradlew initialize

If we want to start the Hybris server, we can simply call:

./gradlew run

To clear directories generated during build and initialization, we can run:

./gradlew cleanGeneratedDirs

I tried to make clean task dependent on this one, but I got a few errors and didn’t spend too much time on investigating them.

As you probably noticed, this solution is just a wrapper around Ant build defined in build.xml file and it’s not pure Gradle build configuration. Nevertheless, these tips may be useful for the people who need to have custom build configurations and dependencies. There’s no doubt that creating and maintaining configurations via Gradle is much easier and more convenient than doing the same job via Ant.

Summary

As we can see, it’s possible to migrate Hybris build from Ant to Gradle, but please remember that Hybris has a custom setup and it may not be the best decision in each case. We should always consider pros and cons of such solution and adjust it to our needs. In legacy systems, we often have to stick to existing setups because making “revolution” may be a huge overhead and doesn’t have to pay off. Moreover, all Hybris extensions also have build configurations based on Ant. On the other hand, I can highly recommend Gradle for greenfield JVM projects.

References

There’s another nice, short article describing migrating Java projects from Ant to Gradle: Easily Convert from Ant to Gradle (objectpartners.com).

Introducing ReactiveAirplaneMode

2017-08-15 Android, Open source, RxJava No comments

I’m continuing Rxfication of the Android. Recently I released brand new library called ReactiveAirplaneMode. As you may guess, it allows listening Airplane mode on Android device with RxJava observables. A usual I’ve hidden all implementation details, BroadcastReceivers and rest of the Android related stuff behind RxJava abstraction layer, so API is really simple. Just take a look on that:

ReactiveAirplaneMode.create()
    .observe(context)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(isOn -> textView.setText(String.format("Airplane mode on: %s", isOn.toString())));

In the code above subscriber will be notified only when airplane mode changes.

If you want to read airplane mode and then listen to it, you can use the following method:

ReactiveAirplaneMode.create()
    .getAndObserve(context)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(isOn -> textView.setText(String.format("Airplane mode on: %s", isOn.toString())));

If you want to check airplane mode only once, you can use get(context) method, which returns Single<Boolean> value:

ReactiveAirplaneMode.create()
    .get(context)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(isOn -> textView.setText(String.format("Airplane mode on: %s", isOn.toString())));

If you want to check airplane mode only once without using Reactive Streams, just call isAirplaneModeOn(context) method:

boolean isOn = ReactiveAirplaneMode.create().isAirplaneModeOn(context);

You can add this library to your project via Gradle:

dependencies {
  compile 'com.github.pwittchen:reactiveairplanemode:0.0.1'
}

If you want to know more details, see sample app, documentation & tests, check repository with the source code at: https://github.com/pwittchen/ReactiveAirplaneMode.

Using Tmux plugins with Tpm

2017-08-07 Linux, Tmux No comments

Recently, I decided to organize my Unix dotfiles in a better way. I had a few custom scripts I used in my Tmux bottom bar. I kept these scripts in .scripts directory and during installation or upgrade of my personal configuration, install.sh script was copying them from .scripts directory to /usr/local/bin/ directory. I wanted to make this configuration more solid and consistent, so I decided to transform these scripts into tmux plugins managed by tpm. I was already using a few plugins like:

In my Tmux bottom bar, I display battery level, uptime, CPU, RAM, IP number and song currently played on Spotify. Previously I just used scripts copied to /usr/local/bin/ and configuration looked like that:

set -g status-right "↑ #(showUptime) ⇅ #(showCpuUsage) ☰ #(showRamUsage) ∴ #(showIp) ↯ #{showBatteryLevel} ⧖ #(date '+%a, %b %d, %H:%M') "

I created the following plugins to replace these scripts:

In order to use Tmux plugins, we need to install Tmux Plugin Manager:

git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm

and initialize it at the bottom of our .tmux.conf file:

run '~/.tmux/plugins/tpm/tpm'

After that, it’s good to reload shell (source ~/.zshrc) and Tmux config (tmux source-file ~/.tmux.conf)

Next, we can add our plugins to .tmux.conf file:

set -g @plugin 'tmux-plugins/tmux-sidebar'
set -g @plugin 'tmux-plugins/tmux-copycat'
set -g @plugin 'tmux-plugins/tmux-pain-control'
set -g @plugin 'tmux-plugins/tmux-urlview'
set -g @plugin 'pwittchen/tmux-plugin-battery'
set -g @plugin 'pwittchen/tmux-plugin-uptime'
set -g @plugin 'pwittchen/tmux-plugin-cpu'
set -g @plugin 'pwittchen/tmux-plugin-ram'
set -g @plugin 'pwittchen/tmux-plugin-ip'
set -g @plugin 'pwittchen/tmux-plugin-spotify'

When we are in Tmux, we can install plugins by pressing prefix + I to install plugins. In my case, prefix = Ctrl+b.
After that, we can hit Enter and we’re ready to go!

Now, I could update my .tmux.conf with the variables defined by my plugins:

set -g status-right " 🔉 #{spotify_song} ↑ #{uptime} ⇅ #{cpu} ☰ #{ram} ∴ #{ip} ↯ #{battery_level} ⧖ #(date '+%a, %b %d, %H:%M') "

After this operation, I could remove custom scripts from my dotfiles and desired functionality is delivered via plugins. Moreover, anyone can install these plugins via tpm without messing with custom scripts!

screenshot from tmux after configuration

Right now, my plugins are in kind of messy state and they don’t work perfectly across all operating systems (e.g. there are problems on macOS), but they’re usable under Linux Ubuntu 16.04 LTS and it’s a good beginning for organizing mess created by the custom scripts.

That’s it! I have plans to publish another article describing how to write your custom Tmux plugin, which can be managed via tpm.