<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Welcome to my blog site on pnkv - Nick&apos;s blog</title><description>Recent content in Welcome to my blog site on pnkv - Nick&apos;s blog</description><link>https://blog.pnkv.de/</link><language>en-us</language><lastBuildDate>Sat, 19 Nov 2022 18:39:15 GMT</lastBuildDate><atom:link href="/index.xml" rel="self" type="application/rss+xml"/><item><title>Using C++ library From Rust - DepthAI RGB Camera Example</title><link>https://blog.pnkv.de/post/2022/11/19/using-cpp-from-rust-depthai-core-rgb-camera-example/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2022/11/19/using-cpp-from-rust-depthai-core-rgb-camera-example/</guid><description>If you want to learn how to use C++ library from Rust - check this article.</description><pubDate>Sat, 19 Nov 2022 18:39:15 GMT</pubDate><content:encoded>There has been a long time since the my last post, and many things happend. I have been persuaded by Alex to join AdVentura Works SA to a very exiting adventure, touching one of my passions in embedded software, robotics, AI/CV/ML. I have left Zest Labs GmbH and joined the new startup, where we are making the warehouse operations more safe and efficient. We have lots of opportunities in the area of tele-operations, AI assited operations, tasks and operation optimisations.

Our new project requires top performance on the edge, and we cannot afford a single *ms* lost in compute. As long time fan of GoLang - I have been challenged to squize even more performance. Our first POCs were written in Go and it performed really well for consumer grade hardware, but when we touch the edge, there is much more to ask. Go is excellent language, producing blazingly fast binaries, but there is still a garbage collector, and much more importantly - memory copy when using C bindings. In our area, there are a lot of modules and libraries written in C and C++. We have to be able to wrap those functionallities and squize the best performance out of them.

All this drove me to Rust - well - not so surprizing. Rust is very close to the hardware, often creates faster binaries than the once written in low level languages like C and C++, and at the same time it is safe and pleasurable to write in.

Our goal is to be able to use existing libraries written in C and C++ in our new applications, without compromizing on performance and safety.

All this made me to experiment, so that I can showcase the interface between already written libraries and our software. Calling external (static or dynamic libraries) is not a trivial problem. C is quite streamlined - in Rust you can use `extern &quot;C&quot;` and be quite sure that the things will work. As for C++ - Rust compiler cannot have a good picture what to interface. Majory of the basic aproaches are to wrap C++ code in C libraries and then to call them from Rust. As you can understand - this is not trivial and requires lots of time and effort. So let&apos;s see what are the options:

- [bindgen](https://lib.rs/crates/bindgen) - Bindgen parses header files and generates Rust bindings. Works well for C but for C++ is not perfect
- [cbindgen](https://lib.rs/crates/cbindgen) - Works in the other direction - parses Rust code and generates C or C++ headers
- [cxx crate](https://lib.rs/crates/cxx) - Works both ways - can generate c++ bindings and vise versa. 
- [cpp crate](https://lib.rs/crates/cpp) - Can embed C++ code in your rust code

Kudos to [Tobias Hunger](https://twitter.com/t_hunger?lang=en) for his [post/presentation](https://slint-ui.com/blog/rust-and-cpp.html).

So lets get our hands durty and write some Rust to call C++ ready library.
I have chosen something that will work for me in my projects. We have bought a [OpenCV AI Kit: OAK—D](https://store.opencv.ai/products/oak-d) to utilise in our project. So the task is to be able to integrate the existing [DepthAI Core Library](https://github.com/luxonis/depthai-core), written in C++, in our Rust core project.

I have taken the short path at the beginning, so that I have less complexity, and just to make the showcase, how to make the things done in the future, so I have chosen to write the existing example app from `depthai-core` in rust - [rgb_encoding.cpp](https://github.com/luxonis/depthai-core/blob/main/examples/VideoEncoder/rgb_encoding.cpp).

The ultimate goal will be to have the same functionallity as in the C++ example, but written in Rust.

For the onces, who don&apos;t want to read more of my rumbles - just check the repository that I have published [Using DepthAI Core from Rust](https://github.com/npenkov/depthai-rgb-encoding-example-rs)

## For the rest - lets explore the code

First we will define a c++ header and implementation, where we will define a class that instantiates the DepthAI Device, and creates a pipeline. Further we will use the same class to fetch the H264/5 frames and write them to a file. Here I have chosen the aproach to control the thread and fetching the frames from Rust - as the call is synchonios - I have the luxory to handle it in Rust. Some of you will criticize me for using a call back function, instead of diretctly fetching the frame data. This has been done intentionally, so that in the future I can change the code to push the frames in a WebRTC pipeline asynchroniously.

[include/depthai_wrapper.h](https://github.com/npenkov/depthai-rgb-encoding-example-rs/blob/main/include/depthai_wrapper.h)

```h
pragma once
#include &quot;rust/cxx.h&quot;
#include &lt;memory&gt;

namespace dev
{
  namespace pnkv
  {

    struct DepthAISource;

    class DepthAIClient
    {
    public:
      DepthAIClient();
      ::std::int32_t next_frame(DepthAISource &amp;src) const;  // [1]

    private:
      class impl;
      std::shared_ptr&lt;impl&gt; impl;
      void push_frame(DepthAISource &amp;src) const;
    };

    std::unique_ptr&lt;DepthAIClient&gt; new_depthai_client();     // [2]

  }
}
```

- [1] `next_frame` function will be called from Rust code to obtain the next Video frame from the camera, which will trigger call back to `post_frame`, which will be Rust bound function
- [2] Method to use for constructing the C++ object - called from Rust code.

[src/deothai_wrapper.cc](https://github.com/npenkov/depthai-rgb-encoding-example-rs/blob/main/src/depthai_wrapper.cc)

```cpp
#include &quot;include/depthai_wrapper.h&quot;
#include &quot;depthai-rust/src/main.rs.h&quot;                        // [3]
#include &lt;algorithm&gt;
#include &lt;functional&gt;
#include &lt;set&gt;
#include &lt;string&gt;
#include &lt;atomic&gt;
#include &lt;thread&gt;
#include &lt;chrono&gt;
#include &lt;memory&gt;
#include &lt;iostream&gt;
#include &lt;unordered_map&gt;
#include &quot;depthai/depthai.hpp&quot;

namespace dev
{
  namespace pnkv
  {

    // Implement simple RawData wrapper for Rust
    class DepthAIClient::impl
    {
      friend DepthAIClient;

    private:
      std::shared_ptr&lt;dai::DataOutputQueue&gt; outputQueue;
      std::shared_ptr&lt;dai::Device&gt; device;
    };

    DepthAIClient::DepthAIClient() : 
      impl(new class DepthAIClient::impl)                    // [4]
    {
      // Create pipeline
      auto pipeline = std::make_shared&lt;dai::Pipeline&gt;();

      // Define sources and outputs
      auto camRgb = pipeline-&gt;create&lt;dai::node::ColorCamera&gt;();
      auto videoEnc = pipeline-&gt;create&lt;dai::node::VideoEncoder&gt;();
      auto xout = pipeline-&gt;create&lt;dai::node::XLinkOut&gt;();

      xout-&gt;setStreamName(&quot;camRgb&quot;);

      // Properties
      camRgb-&gt;setBoardSocket(dai::CameraBoardSocket::RGB);
      camRgb-&gt;setResolution(dai::ColorCameraProperties::SensorResolution::THE_720_P);
      videoEnc-&gt;setDefaultProfilePreset(30, dai::VideoEncoderProperties::Profile::H264_BASELINE);

      // Linking
      camRgb-&gt;video.link(videoEnc-&gt;input);
      videoEnc-&gt;bitstream.link(xout-&gt;input);

      auto deviceInfoVec = dai::Device::getAllAvailableDevices();
      const auto usbSpeed = dai::UsbSpeed::SUPER;
      auto openVinoVersion = dai::OpenVINO::Version::VERSION_2021_4;

      std::map&lt;std::string, std::shared_ptr&lt;dai::DataOutputQueue&gt;&gt; qRgbMap;
      std::vector&lt;std::shared_ptr&lt;dai::Device&gt;&gt; devices;

      // Get the first device
      for (auto &amp;deviceInfo : deviceInfoVec)
      {
        auto device = std::make_shared&lt;dai::Device&gt;(openVinoVersion, deviceInfo, usbSpeed);
        device-&gt;startPipeline(*pipeline);
        impl-&gt;device = device;
        auto outputQueue = impl-&gt;device-&gt;getOutputQueue(&quot;camRgb&quot;, 30, true);
        impl-&gt;outputQueue = outputQueue;
        break;
      }
    }

    // Start fetching encoded frames and pushing them to DepthAISource
    ::std::int32_t 
      DepthAIClient::next_frame(DepthAISource &amp;src) const     // [5]
    {
      push_frame(src);
      return 0;
    }

    void DepthAIClient::push_frame(DepthAISource &amp;src) const
    {
      // Output queue will be used to get the encoded data from the output defined above
      auto h265Packet = impl-&gt;outputQueue-&gt;get&lt;dai::ImgFrame&gt;();
      ::rust::Slice&lt;const ::std::uint8_t&gt; data = 
        ::rust::Slice&lt;const ::std::uint8_t&gt;(h265Packet-&gt;getData().data(), 
              h265Packet-&gt;getData().size());
      post_frame(src, data, h265Packet-&gt;getData().size());    // [6]
      return;
    }

    std::unique_ptr&lt;DepthAIClient&gt; new_depthai_client()
    {
      return std::make_unique&lt;DepthAIClient&gt;();
    }

  }
}
```

- [3] This header will be generated by `cxx`
- [4] Constuct the object and obtain the instance to `Dai::device` and `Dai::outputQueue`
- [5] Method called from rust to fetch the next frame
- [6] `post_frame` is method defined in Rust, that will receive the call when the data is ready from the Camera queue

Now comes the time to use the [cxx](https://crates.io/crates/cxx).

[src/main.rs](https://github.com/npenkov/depthai-rgb-encoding-example-rs/blob/main/src/main.rs)

```rs
#[cxx::bridge(namespace = &quot;dev::pnkv&quot;)]                         // [7]
mod ffi {
    // Rust types and signatures exposed to C++.
    extern &quot;Rust&quot; {
        type DepthAISource;                                     // [8]

        fn post_frame(src: &amp;mut DepthAISource, 
            data: &amp;[u8], size: u32);                            // [9]
    }

    // C++ types and signatures exposed to Rust.
    unsafe extern &quot;C++&quot; {
        include!(&quot;include/depthai_wrapper.h&quot;);                  // [10]

        type DepthAIClient;                                     // [11]

        fn new_depthai_client() -&gt; UniquePtr&lt;DepthAIClient&gt;;    // [12]
        fn next_frame(&amp;self, src: &amp;mut DepthAISource) -&gt; i32;   // [13]
    }
}

pub struct DepthAISource {
    file: std::fs::File,
}

impl DepthAISource {
    pub fn new() -&gt; Self {
        Self {
            file: std::fs::File::create(&quot;video.h264&quot;).unwrap(),
        }
    }
    pub fn close(&amp;mut self) {
        self.file.flush().unwrap();
    }
}

pub fn post_frame(src: &amp;mut DepthAISource, data: &amp;[u8], size: u32) {
    debug(&quot;post_frame: {} {}&quot;, data.len(), size);
    src.file.write_all(data).unwrap();
}
```

- [7] - cxx macro to define the bridge
- [8] - definition of rust structure, that will be passed by reference to C++ methods
- [9] - rust external function call back, that is called from c++ code

__The rest is syntactic sugar, so that we have the code assistance and verification in rust__

- [10] - include the c header
- [11] - define the type that will be implemented in c++
- [12] - the constructor called from rust to instantiate the object
- [13] - function defined in c++ that we will call from rust

How do we build/generate the bridge - at the end `cxx` needs to generate C++ bindings. This is done using the [Rust build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html)

In the project file [build.rs](https://github.com/npenkov/depthai-rgb-encoding-example-rs/blob/main/build.rs) we will use `cxx_build` macro, that needs to be added as development crate.

```rs
    cxx_build::bridge(&quot;src/main.rs&quot;)                             // [13]
        .file(&quot;src/depthai_wrapper.cc&quot;)                          // [14]
        .includes(&amp;[                                             // [15]
            &quot;.&quot;,
            &quot;/usr/include/opencv4&quot;,
            &quot;./deps/depthai-core/build/install/include&quot;,
            &quot;./deps/depthai-core/build/install/include/depthai-shared/3rdparty&quot;,
            &quot;./deps/depthai-core/build/install/lib/cmake/depthai/dependencies/include&quot;,
        ])
        .flag_if_supported(&quot;-std=c++14&quot;)
        .compile(&quot;depthai-rust&quot;);

    println!(&quot;cargo:rerun-if-changed=src/main.rs&quot;);              // [16]
    println!(&quot;cargo:rerun-if-changed=src/depthai.cc&quot;);
    println!(&quot;cargo:rerun-if-changed=include/depthai.h&quot;);
    println!(
        &quot;cargo:rustc-link-search={}&quot;,
        &quot;./deps/depthai-core/build/install/lib&quot;
    );                                                           // [17]
    println!(&quot;cargo:rustc-link-lib=dylib=depthai-core&quot;);         // [18]
    println!(&quot;cargo:rustc-link-lib=dylib=depthai-opencv&quot;);       // [19]
```

- [13] - define the main source to compile with bridge definition
- [14] - add C++ compilation source
- [15] - add the includes needed for the compilation
- [16] - instruct `rustc` to rebuild the sources in case files change
- [17] - add shared libraries location (this is where depthai-core has built the dynamic libraries)
- [18]/[19] - add shared libraries to be linked with

&gt; __Note:__  that before building the project, we have to build the DepthAI core share libraries. (see the [README.md](https://github.com/npenkov/depthai-rgb-encoding-example-rs/blob/main/README.md) and [Makefile](https://github.com/npenkov/depthai-rgb-encoding-example-rs/blob/main/Makefile) in the project)

The project can be built using `cargo build` or you can directly run it using `cargo run` - in both cases, if you have not installed `depthai-core` in the standard location - make sure to adjust the Library path - `LD_LIBRARY_PATH=$(CURRENT_DIR)/deps/depthai-core/build/install/lib`.

The project has been tested only on Linux amd64 system. 

~Enjoy</content:encoded></item><item><title>Maintaining uniqueness using golang and cassandra light weight transactions (LWT)</title><link>https://blog.pnkv.de/post/2020/11/11/golang-cassandra-lwt/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2020/11/11/golang-cassandra-lwt/</guid><description>Read here how to use Light Weight Transaction in cassandra from client written in Go</description><pubDate>Wed, 11 Nov 2020 15:41:00 GMT</pubDate><content:encoded>CCommon case when running a backend system is to require some kind of uniqueness of the records, based on their content. Wheneven having a transactional system, that is pumped with events from other systems/services, every transaction is with generated UUID, but this does not guarantee that the source is unique. There are many cases, where there is backend service that sends data, and if the call fails, the data sending is retried. There are plenty of ways to handle this case with SQL databases, but I would like to explain how we approach the problem in highly scalable system, relying on NoSQL database in AP segment of CAP Theorem - Cassandra.

## The Problem

We would like to store our posts (postID, postText), but we want to guarantee that two requests for creating one and the same post does not result in 2 but just 1 record. (we assume that the ID is generated by our system, and there is no way to recognize if it is the same post, but only checking the content).

## The solution

The functionality is covered by OSS library [CUS](https://github.com/npenkov/cus)

The solution will be relying on Cassandra as DB store, and the service will be implemented in Golang. Our service will implement the following steps:

* Receives a post with content `postContent`
* Based on `postContent` we generate SHA-256 checksum.
* We try to insert the record in cassandra table, where Checksum is the Key in the table with LWT
* If the previous call succeeds, we are OK to insert it in the main table and to return `Success` to the caller
* If the call is not successful - we return the already inserted before record with error indicating that the content is duplicate.

## Database schema

```cql
CREATE TABLE IF NOT EXISTS cus_data(
	obj_id TEXT PRIMARY KEY,
	checksum TEXT,
	data BLOB);

CREATE TABLE IF NOT EXISTS cus_checksum(
	checksum TEXT PRIMARY KEY,
	obj_id TEXT);
```

In `cus_data` we will store the `obj_id` the `checksum` and the real data - `data`, where as in table `cus_checksum` we are going to store the reverse index of `checksum` against `obj_id`.
The crucial part is that we are going to use Lightweight Transactions (LWT), provided by Cassandra, Scylla and AWS Keyspaces, to make sure that we are consistent in inserting records, that are unique. Usually in SQL like database we would use serialized transaction isolation for this, but since we are operating in AP database like cassandra - we can do that only with LWT.

## CQL Statements

Insert checksum and check with LWT if the operation succeded

```cql
INSERT INTO cus_checksum (checksum, obj_id) VALUES (?,?) IF NOT EXISTS
```

Insert the real data record

```cql
INSERT INTO cus_data (obj_id, checksum, data) VALUES (?,?,?)
```

## Go implementation

If you follow the code, the most importat thing is how to use LWT with gocql driver. It can be seen in [Create method of the library](https://github.com/npenkov/cus/blob/main/create.go)

```go
row := make(map[string]interface{})
if applied, err = qry.MapScanCAS(row); err != nil {
  return nil, fmt.Errorf(&quot;failed no data available from LWT : %v&quot;, err)
}
if !applied {
  var ok bool
  var duplicateObjId string
  if duplicateObjId, ok = row[&quot;obj_id&quot;].(string); !ok {
    return nil, fmt.Errorf(&quot;Failed to cast obj_id arg to string : %v&quot;, row)
  }
  return &amp;duplicateObjId, ErrDuplicateObject
}

if err := s.session.Query(insertDataCQL, id, checksum, data).Exec(); err != nil {
  return nil, fmt.Errorf(&quot;failed to insert data : %v&quot;, err)
}
```

&gt; **NOTE**: Here is used `MapScanCAS` instead of `MapScan` or `Scan` method in the gocql driver. This is important if you are doing LWT

## Source code

[Cassandra Unique Store library](https://github.com/npenkov/cus)

~Enjoy</content:encoded></item><item><title>Managing your IdP with terraform</title><link>https://blog.pnkv.de/post/2020/10/31/terraform-keycloak/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2020/10/31/terraform-keycloak/</guid><description>Find out how to use Terraform to deploy and manage your Keycloak IdP</description><pubDate>Sat, 31 Oct 2020 19:55:15 GMT</pubDate><content:encoded>Often when you want to implement authenticaiton/identity provider in your system, you turn to a well tested solution that is already on the market. Writting a good full OAuth2/OIDC/Federation IdP Provider is not a simple task, and if you start from scratch - you can consider it 3-6 months with good size pizza team, that is experienced in the technologies - to go through the whole implementation cycle.
There are plenty of solutions out there, and quite a good ones - Auth0, Google OAuth, Github OAuth, AWS Cognito. Those are all external indentity providers that you can hook into your product, and rely on them. The problem usually is that mojority of Enterprises would like to keep the solution inhouse. They are even not ready to do federation through the public internet.

Here comes one of the solutions for such enterprises - RedHat Keycloak is for quite some while on the market and offers a very decent set of features that one can expect from IdP.

I am not going to go into detail and explain what Keycloak is - feel free to check it out at the [official site](https://www.keycloak.org/).

Well from Operations point of view, especially if you are running on Kubernetes, intallation of Keycloak is traight forward using this [Helm Chart](https://github.com/codecentric/helm-charts/tree/master/charts/keycloak)

When we do that for our customers, we even wrap the helm installation in [terraform](https://www.terraform.io/) code, so that we can automate all the infrastructure and component deployment, and to keep them as code (Infrastructure as code is a main principle of [ZestLabs](https://zestlabs.io))

All said, what we need left is a way to configure our Keycloak Installation, once it is up and running. This can include:

* Creating new Realm with custom login theme
* Client configurations for our OAuth2 clients used in the applications
* Configuring Authentication behaviour
* Configuring federation to other OIDC, LDAP, SAML Providers
* Creating users

Luckyly keycloak is entirely API Driven, and basicly everything that you have in the nice UI Console, you can achieve using API Calls.

There is an open source provider for keycloak, that can be found on [Github](https://github.com/mrparkers/terraform-provider-keycloak), capable of handling all those configurations, that utilizes the API interface.

## Using the provider in your project

Start by introducing the provider in your project. All the follow up snippets are done and tested on Terraform 0.13+.

```tf
terraform {
  required_providers {
    keycloak = {
      source = &quot;mrparkers/keycloak&quot;
      version = &quot;&gt;= 2.0.0&quot;
    }
  }
}
```

&gt; One important note here is - if you are creating a module that will do the job of configuring Keycloak, and then you will use this module in your infrastructure terraform scripts, make sure to include the same snippet to the module itself - this is something introduced since terraform 0.13 and without it, you will start seeing messages like:

```log
Cannot initialize keycloak provider at: hashicorp/keycloak
```

## Configuring your provider agains your Keycloak installation

If your keycloak is freshly installed, most probably you will need to use the admin account that was initially created using password grant:

```tf
provider &quot;keycloak&quot; {
    client_id     = &quot;admin-cli&quot;
    username      = &quot;keycloak&quot;
    password      = &quot;password&quot;
    url           = &quot;http://localhost:8080&quot;
}
```

Replace in the snippet the `url`, `username` and `password` with the once specified in your helm installation. If you need some more flexibility, e.g. providing those credentials from secure provider on execution, then a solution with [Terragrunt](https://github.com/gruntwork-io/terragrunt) can be considered. Anyway this will be a topic for another article.

## Creating your Realm

If you are wandering what Realm is - feel free to visit the [Getting started guide](https://www.keycloak.org/docs/latest/getting_started/#creating-a-realm-and-a-user)

```tf
resource &quot;keycloak_realm&quot; &quot;my_realm&quot; {
  realm             = &quot;my-realm&quot;
  enabled           = true
  display_name_html = &quot;&lt;h1&gt;My Org Realm&lt;/h1&gt;&quot;
  login_with_email_allowed = true
}
```

for more details on the realm config - refer to the provider realm doc [resource &quot;keycloak_realm&quot;](https://registry.terraform.io/providers/mrparkers/keycloak/latest/docs/resources/realm)

### Supply a default root user for the realm

```tf
// Create default user root with the same password as the admin one in master realm
resource &quot;keycloak_user&quot; &quot;root&quot; {
  realm_id = keycloak_realm.my_realm.id
  username = var.root_username
  enabled  = true

  email          = var.root_email
  first_name     = var.root_firstname
  last_name      = var.root_lastname
  email_verified = true

  attributes = {
  }

  initial_password {
    value     = var.keycloak_password
    temporary = true
  }
}
```

## Create OIDC Clients

Mobile realm with clientId: `mobile`, clientSecret: `${var.oidc_secret_mobile}` and mobile oauth schema: `my-mobile-app-schema`

```tf
resource &quot;keycloak_openid_client&quot; &quot;mobile&quot; {
  realm_id  = keycloak_realm.my_realm.id
  client_id = &quot;mobile&quot;

  enabled = true

  access_type           = &quot;CONFIDENTIAL&quot;
  standard_flow_enabled = true
  valid_redirect_uris = [
    &quot;my-mobile-app-schema:/callback&quot;
  ]
  root_url    = &quot;$${authBaseUrl}&quot;
  admin_url   = &quot;$${authBaseUrl}&quot;
  web_origins = [&quot;+&quot;]

  client_secret = var.oidc_secret_mobile
}
```

## Applying the configuration

What was left is just executing the infrastructure/configuration scripts using terraform:

```sh
terraform init
terraform apply
```

After the second step, terraform will present the plan of execution and ask for confirmation.

~Enjoy</content:encoded></item><item><title>Playing with kaniko and kubernetes internal docker registry</title><link>https://blog.pnkv.de/post/2018/06/23/kaniko-private-registry/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2018/06/23/kaniko-private-registry/</guid><description>Playground showing how to use private registry with Google Kaniko - rootless image builder for the cloud.</description><pubDate>Sun, 01 Jul 2018 17:44:45 GMT</pubDate><content:encoded>General idea here is to deploy a docker resgistry inside kubernetes and to use it just for putting the images that we build in the cluster, and to serve them to the same cluster.

Few considerations

 * We are not going to secure the registry, the presumtions will be that your k8s cluster nodes run in a private network. If you want to secure pulling images in a secure way, you have to consider few more steps.

 * Docker resgirstry will be deployed in stateful set. Make sure that your PVC with persistence class are working in your cluster.

 * For building the images we will use [Kaniko](https://github.com/GoogleContainerTools/kaniko)

 * For deploying the docker registry, I would prefer to use my own config, rather than using Helm chart for this.

## Setting up private docker registry in kubernetes

Lets first create a new namespace, to keep docker registry separated:

__000-namespace.yaml__
```yaml
---
apiVersion: v1
kind: Namespace
metadata:
  name: registry
```

```sh
kubectl apply -f 000-namespace.yaml
```

Then we can setup the configurations and the secret we are going to use for the registry

__001-config.yaml__
```yaml
---
apiVersion: v1
data:
  config.yml: |-
    health:
      storagedriver:
        enabled: true
        interval: 10s
        threshold: 3
    http:
      addr: :5000
      headers:
        X-Content-Type-Options:
        - nosniff
    log:
      fields:
        service: registry
    storage:
      cache:
        blobdescriptor: inmemory
    version: 0.1
kind: ConfigMap
metadata:
  labels:
    app: docker-registry
  name: docker-registry-config
  namespace: registry
---
apiVersion: v1
data:
  haSharedSecret: U29tZVZlcnlTdHJpbmdTZWNyZXQK
kind: Secret
metadata:
  labels:
    app: docker-registry
    chart: docker-registry-1.4.3
  name: docker-registry-secret
  namespace: registry
type: Opaque
```

```sh
kubectl apply -f 001-config.yaml
```

Now it is time to deploy docker registry in stateful set:

__002-registry-statefulset.yaml__
```yaml
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: docker-registry
  namespace: registry
spec:
  selector:
    matchLabels:
      app: docker-registry
  serviceName: &quot;registry&quot;
  replicas: 1
  template:
    metadata:
      labels:
        app: docker-registry
      annotations:
    spec:
      terminationGracePeriodSeconds: 30
      containers:
      - command:
        - /bin/registry
        - serve
        - /etc/docker/registry/config.yml
        env:
        - name: REGISTRY_HTTP_SECRET
          valueFrom:
            secretKeyRef:
              key: haSharedSecret
              name: docker-registry-secret
        - name: REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY
          value: /var/lib/registry
        image: registry:2.6.2
        imagePullPolicy: IfNotPresent
        livenessProbe:
          failureThreshold: 3
          httpGet:
            path: /
            port: 5000
            scheme: HTTP
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        name: docker-registry
        ports:
        - containerPort: 5000
          protocol: TCP
        readinessProbe:
          failureThreshold: 3
          httpGet:
            path: /
            port: 5000
            scheme: HTTP
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /var/lib/registry/
          name: data
        - mountPath: /etc/docker/registry
          name: docker-registry-config
      volumes:
      - name: data
        persistentVolumeClaim:
          claimName: docker-registry
      - configMap:
          name: docker-registry-config
        name: docker-registry-config

  volumeClaimTemplates:
  - metadata:
      name: data
      annotations:
        volume.beta.kubernetes.io/storage-class: fast
    spec:
      accessModes: [ &quot;ReadWriteOnce&quot; ]
      storageClassName: generic
      resources:
        requests:
          storage: 20Gi
```

Make sure you have defined storage class `fast` or replace `volume.beta.kubernetes.io/storage-class: fast` in the stateful set descriptor.

```sh
kubectl apply -f 002-registry-statefulset.yaml
```

One last step for the registry will be to define the service and expose it to a node port, so that node dockre can pull the images on `localhost:NODE_PORT`

__003-registry-svc.yaml__
```yaml
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: docker-registry
  name: docker-registry
  namespace: registry
spec:
  externalTrafficPolicy: Cluster
  ports:
  - name: registry
    nodePort: 31500
    port: 5000
    protocol: TCP
    targetPort: 5000
  selector:
    app: docker-registry
  sessionAffinity: None
  type: NodePort
```

```sh
kubectl apply -f 003-registry-svc.yaml
```

Here we have exposed the registry on nodeport `31500`

## Configuring kaniko build

Lets now build an image without exposing docker socket. For this we will use Project [Kaniko](https://github.com/GoogleContainerTools/kaniko).We will use preconfigured namespace `playground` to run the build. First we will define few config maps that we will use for the build. We will play with small application written in Go. So we will use a base `golang` image, and we will execute docker multistage build, where we first compile the application, and then use `alpine` image to run it.

__000-Dockerfile-configmap.yaml__
```yaml
---
apiVersion: v1
data:
  Dockerfile: |-
    FROM golang:latest
    WORKDIR /go/src
    RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

    FROM alpine:latest  
    RUN apk --no-cache add ca-certificates
    WORKDIR /root/
    COPY --from=0 /go/src/app .
    EXPOSE 8080
    CMD [&quot;./app&quot;]  
kind: ConfigMap
metadata:
  name: dockerfile
  namespace: playground
```

```sh
kubectl apply -f 000-Dockerfile-configmap.yaml
```

The real source we will also define in config map, that we will mount in the builder pod:

__001-maingo-configmap.yaml__
```yaml
---
apiVersion: v1
data:
  main.go: |-
    package main

    import (
      &quot;net/http&quot;
      &quot;strings&quot;
    )

    func sayHello(w http.ResponseWriter, r *http.Request) {
      message := r.URL.Path
      message = strings.TrimPrefix(message, &quot;/&quot;)
      message = &quot;Hello &quot; + message
      w.Write([]byte(message))
    }
    func main() {
      http.HandleFunc(&quot;/&quot;, sayHello)
      if err := http.ListenAndServe(&quot;:8080&quot;, nil); err != nil {
        panic(err)
      }
    }

kind: ConfigMap
metadata:
  name: maingo
  namespace: playground
```

```sh
kubectl apply -f 001-maingo-configmap.yaml
```

Now lets run the build:

__002-kaniko-pod.yaml__
```yaml
apiVersion: v1
kind: Pod
metadata:
  name: kaniko
  namespace: playground
spec:
  containers:
  - args:
    - --dockerfile=/go/src/Dockerfile
    - --context=/go/src
    - --destination=docker-registry.registry.svc.cluster.local:5000/test/app:1.0
    image: gcr.io/kaniko-project/executor:latest
    imagePullPolicy: Always
    name: kaniko
    volumeMounts:
    - mountPath: /go/src/Dockerfile
      name: dockerfile
      subPath: Dockerfile
    - mountPath: /go/src/main.go
      name: maingo
      subPath: main.go
  dnsPolicy: ClusterFirst
  restartPolicy: Never
  volumes:
  - configMap:
      name: dockerfile
    name: dockerfile     
  - configMap:
      name: maingo
    name: maingo     
```

```sh
kubectl apply -f 002-kaniko-pod.yaml
```

This will deploy the pod and run the build. You can monitor the build process by running:

```sh
kubectl logs -n playground -f kaniko 
```

After everything is executed successfuly, the builder pod will push the image to the local registry:
`docker-registry.registry.svc.cluster.local:5000/test/app:1.0`

The way afterwards to use the same image, when deploying the pod is:

```yaml
...
  image: localhost:31500/test/app:1.0
...
```

~Enjoy</content:encoded></item><item><title>Gcqlsh</title><link>https://blog.pnkv.de/post/2016/10/23/gcqlsh/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2016/10/23/gcqlsh/</guid><description>Anoucement on releasing the first version of gcqlsh - terminal application for accessing Cassandra/Scilla DB</description><pubDate>Sun, 30 Oct 2016 21:14:45 GMT</pubDate><content:encoded>It has been a long time since the last post. It is time to show my new open source project - [gcqlsh](https://github.com/npenkov/gcqlsh). The idea came when I was preparing some Cassandra docker images and I wanted to stay minimalistic with our CI infrastructure. So I have based my Cassandra docker image on Alpine. Unfortunatly came the frustration with installing python and all the dependencies. On the other hand, I needed an utility for automating the schema creation withing the docker container on first start.
There it came Golang with its beautiful architecture and performance. Write you code. Build it for any architecture - and you have one single performant binary without need of any dependencies.
If you are interested - make sure to visit the project&apos;s github page.
Ideas and contributions are also welcome.

Click on the [image](gcqlsh_rec.gif) to see the animation

~Enjoy</content:encoded></item><item><title>Caching Prepared Sqlite Statements in iOS Application</title><link>https://blog.pnkv.de/post/2013/08/02/caching-prepared-sqlite-statements-in-ios-application/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2013/08/02/caching-prepared-sqlite-statements-in-ios-application/</guid><description>How to cache Prepared statement on iOS when using ObjectiveC</description><pubDate>Fri, 02 Aug 2013 23:08:00 GMT</pubDate><content:encoded>Many applications use Core data for iOS devices, others utilize frameworks like fmdb. But there are also people that write SQLite access from scratch. The comes the answer - how do you cache prepared statements (I will not discuss here why we cache prepared statements)?

Well - I have implemented 2 methods:

  * 1) Using C syntax to maintain array of **sqlite_stmt***
  * 2) Using **NSPointerArray*** to store **sqlite_stmt*** that are prepared

First approach has it&apos;s advantages in regards of using older SDKs (NSPointerArray is available from iOS 6.0+)

Second approach is more elegant, but as mentioned - only for newer versions.

Lets have some code:

_**Using C syntax**_

```objc
// Declare instance variables to store statements - good place is in you Database manager instance
sqlite3_stmt **stmtCached;
int stmtCachedCount;
NSMutableDictionary *stmtSQLPool;
...
@property (atomic, retain) NSMutableDictionary *stmtSQLPool;
...
// in implementation
@synthesize stmtSQLPool;
...
// in constructor initialize the array
stmtCached = (sqlite3_stmt**) malloc(sizeof(sqlite3_stmt*)*MAX_NUM_CACHED_STATEMENT);
```

Code to prepare and cache statements:

```objc
- (sqlite3_stmt*) prepareAndCacheStatementWithSQL: (NSString*) sql andDatabase: (sqlite3*) db {
    @synchronized(self){
        // Try to find if we have cached the statement
        NSNumber *index = [self.stmtSQLPool objectForKey:sql];
        if (index != nil &amp;&amp; stmtCachedCount &gt; index.intValue) {
            // we have already cached statement
            sqlite3_stmt* stmt = stmtCached[index.intValue];
            return stmt;
        }
        // Not prepared yet - prepare it and put it in the pool
        sqlite3_stmt *stmt = [DAO prepareStatementWithNSString:sql andDB: db];
        if (!stmt)
            @throw [NSException exceptionWithName:@&quot;Error preparing statement&quot; 
                                           reason:[NSString stringWithFormat:@&quot;Something went wrong - cannot prepare statement for sql: &apos;%@&apos; - %s&quot;, sql, sqlite3_errmsg(db)] 
                                         userInfo:nil];

        if (stmtCachedCount &gt;= MAX_NUM_CACHED_STATEMENT) {
            NSLog(@&quot;Maximum number of cached statements reached. Stmt for sql %@ will not be cached.&quot;, sql);
        } else {
            stmtCached[stmtCachedCount++] = stmt;
            // store the index
            NSNumber *indexNumber = [NSNumber numberWithInt:(stmtCachedCount-1)];
            [stmtSQLPool setObject:indexNumber forKey:sql];
        }
        return stmt;
    }
}
```

This is pretty much everything. Of course don&apos;t forget to release and finalize statements on db close.

_**In second approach**_ - just instead of using (_sqlite**_) - replace with (_NSPointerArray*_):

```objc
NSPointerFunctionsOptions options = (NSPointerFunctionsStrongMemory |
                                   NSPointerFunctionsStructPersonality);
self.stmtCached = [NSPointerArray pointerArrayWithOptions:options];
```

Fetch and store statements:

```objc
sqlite3_stmt * stmt = [stmtCached pointerAtIndex:i];
...
[stmtCached addPointer:stmt];
```

~Enjoy</content:encoded></item><item><title>Migrating From Svn to Git</title><link>https://blog.pnkv.de/post/2013/04/21/migrating-from-svn-to-git/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2013/04/21/migrating-from-svn-to-git/</guid><description>The post shows how to migrate your SVN repository to Git.</description><pubDate>Sun, 21 Apr 2013 13:05:48 GMT</pubDate><content:encoded>Suppose you have a SVN repository and you would like to move to GIT - there might be many arguments around this. Well - here are some steps that I have tried to synthesise after many attempts and reading in internet. I am sure there are many approaches, but this one works for me straight forward.

The whole procedure consists of several steps:

  * Extracting users from SVN and creating a mapping file SVN_USER &lt;-&gt; GIT_USER
  * Cloning SVN repository into GIT repository
  * Migrating branches
  * Migrating tags
  * Creating new GIT detached repository and pushing all changes to it

Here are some assumptions:
  
You will work in one directory, where you will create

`Suppose you have a SVN repository and you would like to move to GIT - there might be many arguments around this. Well - here are some steps that I have tried to synthesise after many attempts and reading in internet. I am sure there are many approaches, but this one works for me straight forward.

The whole procedure consists of several steps:

  * Extracting users from SVN and creating a mapping file SVN_USER &lt;-&gt; GIT_USER
  * Cloning SVN repository into GIT repository
  * Migrating branches
  * Migrating tags
  * Creating new GIT detached repository and pushing all changes to it

Here are some assumptions:
  
You will work in one directory, where you will create

`YOUR_SVN_REPOSITORY_URL` - is the URL that you use to checkout from SVN.

Lets start

_**Extracting users from SVN and creating a mapping file SVN_USER &lt;-&gt; GIT_USER**_

GIT needs to know how to map users from SVN to it&apos;s format. Usually users in SVN are just usernames, where in GIT they are in format

`John Smith &lt;john.smith@mail.something&gt;;`

So at the end we should produce a mapping file that looks like:

```
jsmith = John Smith &lt;john.smith@mail.something&gt;;
ltorvalds = Linus &lt;linus@linux.org&gt;;
```

So execute the following command in your checkout svn repository, in order to create a file with the mapping `svn-git-users-mapping.txt`

```sh
svn log -q | awk -F &apos;|&apos; &apos;/^r/ {sub(&quot;^ &quot;, &quot;&quot;, $2); sub(&quot; $&quot;, &quot;&quot;, $2); print $2&quot; = &quot;$2&quot; &lt;&quot;$2&quot;&gt;&quot;}&apos; | sort -u &gt; svn-git-users-mapping.txt
```

Edit the produced file with correct User names and emails on the right side.

_**Cloning SVN repository into GIT repository**_

The following code executed in terminal will first create a directory, and clone svn into git repository in this directory, using `svn-git-users-mapping.txt` file for transforming users.

```sh
mkdir YOUR_GIT_REPO_DIR 
git svn clone YOUR_SVN_REPOSITORY_URL -A svn-git-users-mapping.txt --stdlayout YOUR_GIT_REPO_DIR
```

This script uses the standard SVN layout (trunk, branches, tags) - if you have a different structure - you can explicitly specify it, using parameters (-T trunk -b branches -t tags)

_**Migrating branches**_

Now is time to migrate branches - enter the created directory (YOUR\_GIT\_REPO_DIR) and execute the following script (this is a bash script, so if you use another shell, maybe you have to adjust it):

```sh
for branch in `git branch -r | grep -v -e &apos;tags\/\(.*\)&apos; | sed &apos;s/  \(.*\)/\1/g&apos;`
do
        remote_branch=&quot;remotes/$branch&quot;
        echo &quot;About to checkout branch $remote_branch into $branch&quot;
        echo &quot;=============================================&quot;
        git checkout -b &quot;$branch&quot; &quot;$remote_branch&quot;
done
```

Similar process is used for the next point too:

_**Migrating tags**_

```sh
for branch in `git branch -r | grep -e &apos;\(tags\/\)\(.*\)&apos; | sed &apos;s/\(tags\/\)\(.*\)/\2/g&apos;`
do
    remote_branch=&quot;remotes/tags/$branch&quot;
    new_tag=&quot;tag_$branch&quot;
    echo &quot;About to checkout tag $remote_branch into $new_tag&quot;
    echo &quot;=============================================&quot;
    git checkout -b &quot;$new_tag&quot; &quot;$remote_branch&quot;
    git checkout master
    git tag $branch &quot;$new_tag&quot;
    git branch -D &quot;$new_tag&quot;
done
```

Now that we have fully migrated repository, if we want a detached one from SVN (currently the created repo is connected to svn and can be used that way, with commends `git svn rebase --all` - to fetch and rebase all changes from SVN, and `git svn dcommit --interactive` - to push changes from git local commits to remote SVN repo).

Next step:

_**Creating new GIT detached repository and pushing all changes to it**_

```sh
git init --bare NEW_GIT_REPO
cd NEW_GIT_REPO
git symbolic-ref HEAD refs/heads/trunk

cd YOUR_GIT_REPO_DIR
git remote add NEW_GIT_REPO ../NEW_GIT_REPO
git config remote.NEW_GIT_REPO.push &apos;refs/remotes/*:refs/heads/*&apos;
git push NEW_GIT_REPO
```

Now you are ready to use the newly created GIT repository, having all your history, branches and tags.

In next article I will try to share my experience of using SVN as central repository, and GIT as local versioning and client.

Here are some links that I used, while researching the best way to do the migration:

- [Converting a Subversion repository to Git](http://john.albin.net/git/convert-subversion-to-git)

- [Stackoverflow: How to migrate SVN with history to a new Git repository?](http://stackoverflow.com/questions/79165/how-to-migrate-svn-with-history-to-a-new-git-repository)

- [Experimenting with Git at Slide Part 1/3](http://unethicalblogger.com/2008/07/27/experimenting-with-git-at-slide-part-1-3.html)

- [Tool to manage svn-externals with git](https://github.com/andrep/git-svn-clone-externals)

~Enjoy</content:encoded></item><item><title>How to Speed Up Android Emulator on UX System</title><link>https://blog.pnkv.de/post/2012/08/05/how-to-speed-up-android-emulator-on-ux-system/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2012/08/05/how-to-speed-up-android-emulator-on-ux-system/</guid><description>Ways to increase your mobile development velocity by making Android emulator work faster</description><pubDate>Sun, 05 Aug 2012 11:29:01 GMT</pubDate><content:encoded>If you are developing for Android, you probably have already abandoned the emulator that comes with Android SDK, and are testing and debugging on a real device. I cannot blame you - the emulator is awfully slow. Well I have good news for you - you can speed it up, if you are using uX system (Unix like - Linux, Mac OS X, BSD).
  
The trick is very simple - and I suppose some of you have already activated it - **mount /tmp folder into memory**. The reason why the emulator is much more faster - is that when the emulator is started, the image is expanded into **/tmp** folder - and all the communication goes through there. Normally it goes through DiskIO, and the trick is to do it through much faster channel - memory.

Here is the way to do it in Linux:

```sh
sudo gedit /etc/fstab
```

add the following line at the bottom:

```sh
tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0
```

This will mount your /tmp folder into memory.

Now you can type:

```sh
sudo mount /tmp
```

or restart the system. Enjoy the difference.

And here how it is done under Mac OS X (you can visit one article here - &lt;a href=&quot;http://laclefyoshi.blogspot.de/2011/05/tmpfs-on-linux-and-mac.html&quot; title=&quot;tmpfs on Linux and Mac&quot; target=&quot;_blank&quot;&gt;http://laclefyoshi.blogspot.de/2011/05/tmpfs-on-linux-and-mac.html&lt;/a&gt;):

```sh
sudo hdid -nomount ram://256000
```

this will give you something like /dev/rdisk2 - then use &quot;2&quot; in the following command instead of &quot;X&quot;:

```sh
sudo newfs_hfs /dev/diskX
sudo mount -t hfs /dev/diskX /tmp

```

This is something you should do every time you restart the system.

~Enjoy</content:encoded></item><item><title>Setting Environment Variables in Mac Os X</title><link>https://blog.pnkv.de/post/2012/03/17/setting-environment-variables-in-mac-os-x/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2012/03/17/setting-environment-variables-in-mac-os-x/</guid><description>Simple reference on how to handle Environment variables on MacOSX, compared to Linux/Unix environments.</description><pubDate>Sat, 17 Mar 2012 21:32:49 GMT</pubDate><content:encoded>Once you have experience (or not) with some uX system, at some point you have to deal with environment variables, especially if you intend to do some development. I used to come from Open Source uX systems, and some old ones like HPUX, AIX, Solaris. When I switched to OS X, which is to some extent BSD - I had to find the best way to deal with env. variables. So - here are the ones that I use

_**Variables set in your terminal access**_

Say you are using some variables usually in terminal access. Then you can use the same way of setting them, as on any other uX System - in your shell profile scripts (the one that is executed at the beginning, when you start terminal). In my case I use `bash` - so the file that I use to set env variables is 

`$HOME/.bash_profile`

You can simple add lines to this file (or create it, if it does not exist):

```sh
export TOMCAT_HOME=/opt/apache-tomcat
```

Setting environment variables that should be available also in programs outside terminal - say you want to have them in Eclipse IDE, or in some other program - then we do it in
  
`/etc/launchd.conf`

the syntax there is different:

```sh
setenv ANDROID_HOME /opt/android-sdks
```

this will require root access and restarting the launchd or system, in order to have them active.

~Enjoy</content:encoded></item><item><title>First steps in creating Web service JSON enabled iOS application</title><link>https://blog.pnkv.de/post/2012/01/28/first-steps-in-creating-web-service-json-enabled-ios-application/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2012/01/28/first-steps-in-creating-web-service-json-enabled-ios-application/</guid><description>Read this if you want to find out my first steps on creating iOS mobile application backed by java application in the cloud</description><pubDate>Sat, 28 Jan 2012 13:07:35 GMT</pubDate><content:encoded>This article continues the series for creating a web service consuming program on your mobile device. In the [previous article](/2012/01/25/first-steps-in-creating-your-web-service-enabled-mobile-application-using-json-geronimo-android-and-resteasy/) I have showed you how to create Server part (web service) on Geronimo and how to access it from Android app. Now we shall do the same with iOS application.

So what do you need.

  * Mac with OSX
  * XCode IDE with iOS SDK
  * [Code and applications (server, IDE, code) from previous article in order to run the server](/2012/01/25/first-steps-in-creating-your-web-service-enabled-mobile-application-using-json-geronimo-android-and-resteasy/)

So lets start. First create iOS Project - I prefer here to use &quot;Single View Controller&quot; template:

![](demo-createNewProject.png)

Then put you properties for the new project:

![](demo-setProjectProps.png)

Now we shall define UI variables that we shall use. Open `ViewController.h` and modify it like shown bellow

```objc
#import &amp;lt;UIKit/UIKit.h&gt;

@interface ViewController : UIViewController {

    IBOutlet UITextField *txtIPAddress;
    IBOutlet UITextView *txtDisplayArea;
    IBOutlet UIButton *btnRunWebService;

}

@property (nonatomic, retain) UITextField *txtIPAddress;
@property (nonatomic, retain) UITextView *txtDisplayArea;
@property (nonatomic, retain) UIButton *btnRunWebService;

- (IBAction)runWebServiceAction:(id)sender;

@end
```

Here we define the same controls that we used in Android demo - one TextField for entering IPAddress of the server, one TextView where we should display the response from server and a button, that will trigger web service call. I will not describe why and how Objective-C is used to define these - there are plenty of books and demos on the net to find this out.

Next we shall create the UI in out `ViewController.xib`. Open it and draw the controls shown on screenshots, using drag and drop from your right-bottom panel with Library controls:

![](demo-composeUI.png)

The next step is to create the binding UI &lt;-&gt; Class implementation. Open the tree with controls, right click on &quot;Placeholders&quot; -&gt; &quot;File&apos;s Owner&quot; and drag to TextField (IPAddress). Xcode will offer to connect it to attribute `txtIPAddress`. Repeat this for TextView (area) and for the button. Now do the reverse operation - drag from Button to &quot;File&apos;s Owner&quot; in order to connect the Push button operation to method that we defined in `ViewController.h`.

Now we shall define the value class `MsgObj` with 2 attributes - id and message text.

`MsgObj.h`

```objc
#import &amp;lt;Foundation/Foundation.h&gt;

@interface MsgObj : NSObject {
    NSNumber *msgId;
    NSString *msgTxt;
}

@property (nonatomic, retain) NSNumber *msgId;
@property (nonatomic, retain) NSString *msgTxt;

- (id)initWithJSON:(NSDictionary*)dataDict;

@end
```

`MsgObj.m`

```objc
#import &quot;MsgObj.h&quot;

@implementation MsgObj

@synthesize msgId;
@synthesize msgTxt;

- (id)initWithJSON:(NSDictionary*)dataDict{
    if (self = [super init]) {
        self.msgId = [dataDict objectForKey:@&quot;id&quot;];
        self.msgTxt = [dataDict objectForKey:@&quot;msgText&quot;];
    }
    
    return self;
}

- (void)dealloc{
    [msgId release];
    [msgTxt release];
    [super dealloc];
}

@end
```

What we do here is to define constructor `initWithJSON` that we will use to create with objects, when we receive data from web service call.

We are ready to program the call know. First put the following line on the top of `ViewController.m`. This will define macro for async call queue:

```objc
#define kBackGroudQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)```

Then we should &quot;synthesize&quot; the attributes just after the class implementation definition:

```objc
@implementation ViewController

@synthesize txtDisplayArea;
@synthesize txtIPAddress;
@synthesize btnRunWebService;
```

We should not forget to manage the memory - define the `dealloc` method

```objc
-(void)dealloc {
    [txtIPAddress release];
    [txtDisplayArea release];
    [btnRunWebService release];
    
    [super dealloc];
}
```

At the end - we will put the call to web service. There we use the TextField to obtain the server IP address, and to execute the call in Async call, using the macro we defined before:

```objc
- (IBAction)runWebServiceAction:(id)sender {
    NSString *ipAddress = [txtIPAddress text];;
    NSString *urlString = [NSString stringWithFormat:@&quot;http://%@:8080/testweb/re/first/tellMe&quot;, ipAddress];
    NSLog(@&quot;Call URL: %@&quot;, urlString); //3
    NSURL *url = [NSURL URLWithString:urlString];
    dispatch_async(kBackGroudQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: url];
        [self performSelectorOnMainThread:@selector(receiveData:) 
                               withObject:data waitUntilDone:YES];
    });
}
```

Here we also have set that when response is received - it will be received in method `receiveData:`

```objc
- (void)receiveData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization 
                          JSONObjectWithData:responseData
                          options:kNilOptions 
                          error:&amp;error];
    MsgObj *msg = [[MsgObj alloc] initWithJSON:json];
    [txtDisplayArea setText:[msg msgTxt]];
}
```

When we receive data - we parse it to JSON and construct our MsgObj. At the end we show the result by setting TextView with text contained in the message.
  
When you run this it will look like:

![](demo-runSimulator.png)

Obtain your IP address by typing `ifconfig` into Terminal.

Put it in the TextField for IP Address and push the button. (Don&apos;t forget to start the web server and web application before - this you should know from [previous article](/post/2012/01/25/first-steps-in-creating-your-web-service-enabled-mobile-application-using-json-geronimo-android-and-resteasy/)).

![](demo-runWebService.png)

You can download source code for this project [here](/uploads/2012/01/testIOS.tar.gz &quot;iOS Demo application source code&quot;).

~Enjoys</content:encoded></item><item><title>First steps in creating your web service enabled mobile application using JSON, Geronimo, Android and RESTEasy</title><link>https://blog.pnkv.de/post/2012/01/25/first-steps-in-creating-your-web-service-enabled-mobile-application-using-json-geronimo-android-and-resteasy/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2012/01/25/first-steps-in-creating-your-web-service-enabled-mobile-application-using-json-geronimo-android-and-resteasy/</guid><description>Read this if you want to find out my first steps on creating Android mobile application backed by java application in the cloud</description><pubDate>Wed, 25 Jan 2012 17:23:20 GMT</pubDate><content:encoded>This articles will reveal the first steps in setting up your development environment for building WebService/Enterprise Java applications and consuming their services from Android device. What I am using in this example:

  * Geronimo with Jetty7 javaee5 - 2.2.1 - as application/web server
  * Eclipse Indigo EE (with WTP plugin)
  * Android SDK 4.0.3
  * Google Gson 2.1
  * Resteasy - jaxrs - 2.3.1.GA

Please don&apos;t be bored from so many screenshots. If you know the basics you just can skip them. Please also don&apos;t try to rewrite any code from them - source code is available for download at the end of the article.

So first step is to download and setup all these packages. If you are new to Java - then you should start by downloading Java 6 or Java 7 from &lt;a title=&quot;Oracle Download site&quot; href=&quot;http://www.oracle.com/technetwork/java/javase/downloads/index.html&quot; target=&quot;_blank&quot;&gt;Oracle Download site&lt;/a&gt;.

The proceed with Eclipse EE - &lt;a title=&quot;Eclipse Download site&quot; href=&quot;http://www.eclipse.org/downloads/&quot; target=&quot;_blank&quot;&gt;download site&lt;/a&gt;.

Get &lt;a title=&quot;Android SDK&quot; href=&quot;http://developer.android.com/sdk/index.html&quot; target=&quot;_blank&quot;&gt;Android&lt;/a&gt; and follow the instructions to install it and add ADT plugin to your Eclipse IDE.

Download and unpack Google &lt;a title=&quot;Google Gson Download site&quot; href=&quot;http://code.google.com/p/google-gson/downloads/list&quot; target=&quot;_blank&quot;&gt;GSon&lt;/a&gt;, &lt;a title=&quot;JBoss Rest Easy site&quot; href=&quot;http://www.jboss.org/resteasy&quot; target=&quot;_blank&quot;&gt;Reaseasy&lt;/a&gt; and &lt;a title=&quot;Apache Geronimo Download site&quot; href=&quot;http://geronimo.apache.org/downloads.html&quot; target=&quot;_blank&quot;&gt;Geronimo&lt;/a&gt;.

And now is where the fun starts.

&lt;p style=&quot;text-align: center;&quot;&gt;
  &lt;strong&gt;The Web Service&lt;/strong&gt;First we will create a web application with one simple webservice that will serve JSON data. I suppose at this step that you have setup your Eclipse and integrated it with Geronimo. (if you have troubles with finding information, please consult with &lt;a title=&quot;Geronimo 2.2 User&apos;s Guide - Development environment&quot; href=&quot;https://cwiki.apache.org/GMOxDOC22/development-environment.html&quot; target=&quot;_blank&quot;&gt;the link to Geronimo 2.2 documentation&lt;/a&gt;).

Start Eclipse EE and create your Geronimo server - goto server tab in the bottom panel, righ-click and select New -&gt; Server:
  
![](03-CreateGeronimoServer.png)

Select the location that you have extracted Geronimo server in:
  
![](04-SelectGeronimoLocation.png)

Create a new Web -&gt; Dynamic Web Project.
  
![](01-CreateWebProject.png)

Set the web project name and make sure to select target server to **Apache Geronimo server** that you have created
  
![](02-WebProject-SetTheName.png)

Now we should import Resteasy libraries into our Web Project - just get the libs from the location that you have extracted resteasy package and drop them into `&lt;strong&gt;WebContent\WEB-INF\lib&lt;/strong&gt;` folder in package explorer. When asked - select &quot;Copy&quot; files.

![](05-AddResteasyLibsToProject1.png)

Here comes the fun part.
  
Let&apos;s code the classes. We shall begin with the data container object for our data exchange. We shall create a simple bean (MsgObj) that will contain 2 attributes - id and msgText.

![](06-CreateMsgClass.png)

```java
package com.npenkov.testweb;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = &quot;msg&quot;)
public class MsgObj {
	private int id;
	private String msgText;
	
	@XmlAttribute
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	@XmlAttribute
	public String getMsgText() {
		return msgText;
	}
	public void setMsgText(String msgText) {
		this.msgText = msgText;
	}
}
```

As we have out container, now we shall create the Service class. It will contain just one simple method that will return a new instance of our `MsgObj` with some data in it.

```java
package com.npenkov.testweb;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path(&quot;/first&quot;)
@Consumes({&quot;application/json&quot;})
@Produces({&quot;application/json&quot;})
public class FirstService {
	
	@GET
	@Path(&quot;/tellMe&quot;)
	public MsgObj tellMe() {
		MsgObj m = new MsgObj();
		m.setId(1);
		m.setMsgText(&quot;Hello, friend!&quot;);
		return m;
	}
}
```

Important for web service (resteasy) is to create the so called`` class, that will know what services we should expose. It is mandatory that it extends `javax.ws.rs.core.Application`. You should mention here in the constructor that we add our service class to list of web service classes that Application will provide.

```java
package com.npenkov.testweb;

import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;

public class WebServicesApp extends Application {
	HashSet &lt;Object&gt; singletons = new HashSet&lt;Object&gt;();
    
	public WebServicesApp() {
		singletons.add(new FirstService());
	}

	@Override
	public Set&lt;Class&lt;?&gt;&gt; getClasses() {
		HashSet&lt;Class&lt;?&gt;&gt; set = new HashSet&lt;Class&lt;?&gt;&gt;();
		return set;
	}

	@Override
	public Set &lt;Object&gt; getSingletons() {
  		return singletons;
  	}
  }
  ```
      
      
Time for setting the `web.xml` descriptor. There we should register Resteasy servlet that will get the requests and execute our web services. If you take a look at the code fragment - we register our Application in parameter `javax.ws.rs.core.Application`.
      
      
```xml
   &lt;context-param&gt;
      &lt;param-name&gt;javax.ws.rs.core.Application&lt;/param-name&gt;
      &lt;param-value&gt;com.npenkov.testweb.WebServicesApp&lt;/param-value&gt;
   &lt;/context-param&gt;

   &lt;context-param&gt;
      &lt;param-name&gt;resteasy.servlet.mapping.prefix&lt;/param-name&gt;
      &lt;param-value&gt;/re&lt;/param-value&gt;
   &lt;/context-param&gt;

   &lt;listener&gt;
      &lt;listener-class&gt;
         org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
      &lt;/listener-class&gt;
   &lt;/listener&gt;

   &lt;servlet&gt;
      &lt;servlet-name&gt;Resteasy&lt;/servlet-name&gt;
      &lt;servlet-class&gt;
         org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
      &lt;/servlet-class&gt;
   &lt;/servlet&gt;

   &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;Resteasy&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/re/*&lt;/url-pattern&gt;
   &lt;/servlet-mapping&gt;
```

Ready to start the server and deploy out web application. Right click on &lt;code&gt;testweb``` in Package Explorer and right-click there. Then select &quot;Run as&quot; -&gt; &quot;Run on server&quot;. Finish the process.

![](10-RunOnServer.png)
      
      
Wait for Geronimo to boot - you will see lots of messages in &quot;Console&quot; view in the bottom.
When it is ready - we can test our small web service. Open your browser and type the following url:
&lt;a title=&quot;Test your service url&quot; href=&quot;http://localhost:8080/testweb/re/first/tellMe&quot;&gt;http://localhost:8080/testweb/re/first/tellMe&lt;/a&gt;

&lt;ul&gt;
    &lt;li&gt;
      Usually default port for Jetty (web server) is set to 8080.
    &lt;/li&gt;
    &lt;li&gt;
      In the URL first we have our server and port.
    &lt;/li&gt;
    &lt;li&gt;
      Then is the webApplication name.
    &lt;/li&gt;
    &lt;li&gt;
      Then the mapping context that we specified in web.xml
    &lt;/li&gt;
    &lt;li&gt;
      the last two tokens are our service (&quot;first&quot;) and method (&quot;tellMe&quot;) - these are the words that we put as &lt;code&gt;@Path``` in &lt;code&gt;FirstService```class.
    &lt;/li&gt;
&lt;/ul&gt;      

![](11-TestViaBrowser.png)

So we are ready now to start consuming web service from our web device. But first we have to write the client code in Android Application.

&lt;p style=&quot;text-align: center;&quot;&gt;
&lt;strong&gt;The Android Application&lt;/strong&gt;

Start by creating new &quot;Android Project&quot;.

![](12-AndroidProject.png)

Make sure to select the runtime for the project. It might be that you have to consult here with Android Development documentation on how to create Virtual Device.

![](13-SelectRuntime.png)

Continue with defining the main UI elements. We are not going to do something with lots of screens or functionallities - just one screen, with one input box for your WebService server IP address, one area that we will present responses there and finally - a button that will trigger WebService call. So starting with &lt;code&gt;res/layout/main.xml```

```xml
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:orientation=&quot;vertical&quot; &gt;
    &lt;LinearLayout
        android:id=&quot;@+id/linearLayout1&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        android:orientation=&quot;vertical&quot; &gt;
        &lt;LinearLayout
            android:id=&quot;@+id/linearLayout2&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;wrap_content&quot; &gt;
            &lt;TextView
                android:id=&quot;@+id/lblIPAddress&quot;
                android:layout_width=&quot;wrap_content&quot;
                android:layout_height=&quot;wrap_content&quot;
                android:text=&quot;IP Address&quot; /&gt;
            &lt;EditText
                android:id=&quot;@+id/editIPAddress&quot;
                android:layout_width=&quot;wrap_content&quot;
                android:layout_height=&quot;wrap_content&quot;
                android:layout_weight=&quot;1&quot; &gt;
                &lt;requestFocus /&gt;
            &lt;/EditText&gt;
        &lt;/LinearLayout&gt;
        &lt;TextView
            android:id=&quot;@+id/textView&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;0.42&quot;
            android:text=&quot;TextView&quot; /&gt;
        &lt;Button
            android:id=&quot;@+id/btnCallService&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;Call Service&quot; /&gt;
    &lt;/LinearLayout&gt;
&lt;/LinearLayout&gt;
```

Now we should make sure to have access to google-gson - library that will help us move JSON formatted data into runtime objects. Right-click on Android project -&gt; Properties. And set Java Build Path - add to libraries the jar file that you have extracted from google-gson archive.

![](16-AddGsonLib.png)

Now some more about the WebService call classes and Interfaces. What I did - is to define one class called  &lt;code&gt;WebService```. This class will be responsible for client &lt;-&gt; server communication. As of several releases - it is not allowed to make Asynchronic Network from main UI Thread - we should separate this logic, and executed in Async Task - means - extends &lt;code&gt;android.os.AsyncTask```. If you need more info on Threads in Android - there are great articles and demos on Android Development Web site.
Second major point in our simple architecture, is to define an interface for communication between UI and WebService call. We define the Interface 
```java

package com.npenkov.mobile;

public interface ICallbackHandler {
	public void response(String response);
}
```

In other words - our UI class will implement this interface and pass self instance to AsyncThread. When AsyncThread webservice class finishes his work - he will call implementation method &lt;code&gt;response(String)``` of our UI class to notify about the result.
I have to admit here that some of the code for WebService Call - I have copied from &lt;a href=&quot;http://www.josecgomez.com/2010/04/30/android-accessing-restfull-web-services-using-json/&quot;&gt;Jose C Gomez&apos;s Blog&lt;/a&gt;.

Now let us reveal the Mobile Magic.
First the declaration of the Activity (main execution View) - we are implementing here two Interfaces. One for listening of Click events (further we should tell to button to send events to this class) and one for listening for responses from Async Web Service call.

```java
package com.npenkov.mobile;

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class TestmobileActivity extends Activity 
		implements OnClickListener, ICallbackHandler {
	private Button btnRunWebService;
	private TextView txtField;
	private TextView txtServerIP;
	private AlertDialog.Builder builder;
```

The `onCreate` method is executed in the begging of the Activity execution. There we obtain instances to UI objects from the view. Set that Activity will be the class for listening to Button click events.

```java
@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);
	
	builder = new AlertDialog.Builder(this);

	btnRunWebService = (Button) findViewById(R.id.btnCallService);
	txtField = (TextView) findViewById(R.id.textView);
	txtServerIP = (TextView) findViewById(R.id.editIPAddress);

	btnRunWebService.setOnClickListener(this);
}
```

Next - what should happen when the button is clicked - show confirmation dialog box and start the web service call:

```java
public void onClick(View v) {
	builder.setMessage(&quot;Run REST request?&quot;).setCancelable(false)
			.setNegativeButton(&quot;OK&quot;, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
					callWebService();
				}
			});
	AlertDialog alert = builder.create();
	alert.show();
}
```

And at the end - the Web Service call and response methods. When we call the service - we will take the IP address from the field that we defined. When we receive a response - a MsgObj - we will deserialize it using Gson and put the message text in the text field on the screen.
```java
private void callWebService() {
	Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;();
	String serverIP = txtServerIP.getText().toString();
	WebService webService = new WebService(
			&quot;http://&quot;+ serverIP+&quot;:8080/testweb/re/first/&quot;, 
			&quot;tellMe&quot;, params, this, WebService.GET_METHOD);
	webService.execute();
}

@Override
public void response(String response) {
	Log.i(&quot;callMethod&quot;, &quot;response&quot;);
	try {
		MsgObj msg = new Gson().fromJson(response, MsgObj.class);
		txtField.setText(msg.getMsgText());
	} catch (Exception e) {
		Log.d(&quot;Error: &quot;, &quot;Processing of &quot; + response );
		if (e != null &amp;&amp; e.getMessage() != null) Log.d(&quot;Error: &quot;, e.getMessage() );
		else if (e != null) Log.d(&quot;Error: &quot;, e.toString());
		else Log.d(&quot;Error: &quot;, &quot;Null Exception&quot;);
	}
}
```      

At last we should enable our application to call web services on Internet. For almost all resource like operations, you should inform Android OS that you request this permission. If not - you will not have access to these services. So open your &lt;code&gt;AndroidManifest.xml``` and add the following line

```xml
	&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;&gt;&lt;/uses-permission&gt;
```

We are ready to test our application. Make sure Geronimo is running. Right click on &lt;code&gt;testmobile``` project and execute it (&quot;Run As&quot; -&gt; &quot;Android Application&quot;).

Obtain your IP address by executing command `ipconfig` if you are on Windows machine. And `ifconfig` if running MacOS or some UX type of OS.

Write down the address and push the button on your Android Emulator:

![](21-Android-Running1.png)

When you confirm this message box - you should see the message text from Web Service into text field that we defined on the screen:

![](22-AndroidResponse.png)

 - [Here](/uploads/2012/01/testmobile.zip) you can download source code for Android application.
 - And [here](/uploads/2012/01/testweb.zip) you can download source code for WebService application.


[Follows](/post/2012/01/28/first-steps-in-creating-web-service-json-enabled-ios-application) an article to do the same app, but on iOS.

~Enjoy</content:encoded></item><item><title>Running ABAP queries with dynamic WHERE clause - UPDATED 2</title><link>https://blog.pnkv.de/post/2011/11/24/running-abap-queries-with-dynamic-where-clause/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2011/11/24/running-abap-queries-with-dynamic-where-clause/</guid><description>Tips and tricks in SAP ABAP Dynamic development</description><pubDate>Thu, 24 Nov 2011 16:26:57 GMT</pubDate><content:encoded>Here comes a short and simple example for ABAP Programming. Suppose you want to make some more flexible function module for searching data in database table, that depending on parameters that are passed (can be optional), forms the WHERE clause of select statement. In ABAP this is pretty straight forward:

```abap
FUNCTION zsfli_sflight_getlist.
*&quot;----------------------------------------------------------------------
*&quot;*&quot;Local Interface:
*&quot; IMPORTING
*&quot; VALUE(P_CARRID) TYPE ZSFLIGHT-CARRID OPTIONAL
*&quot; VALUE(P_CONNID) TYPE ZSFLIGHT-CONNID OPTIONAL
*&quot; VALUE(P_FLDATE) TYPE ZSFLIGHT-FLDATE OPTIONAL
*&quot; TABLES
*&quot; FLIGHT_DATA STRUCTURE ZSFLIGHT
*&quot; RETURN STRUCTURE BAPIRET2
*&quot;----------------------------------------------------------------------
  DATA l_where(100) OCCURS 0 WITH HEADER LINE.

  IF p_carrid IS NOT INITIAL.
    APPEND &apos;carrid = p_carrid&apos; TO l_where.
  ENDIF.
  IF p_connid IS NOT INITIAL.
    IF l_where IS INITIAL.
      APPEND &apos; and &apos; TO l_where.
    ENDIF.
    APPEND &apos;connid = p_connid&apos; TO l_where.
  ENDIF.
  IF p_fldate IS NOT INITIAL.
    IF l_where IS INITIAL.
      APPEND &apos; and &apos; TO l_where.
    ENDIF.
    APPEND &apos;fldate = p_fldate&apos; TO l_where.
  ENDIF.

  SELECT * FROM sflight INTO CORRESPONDING FIELDS OF TABLE flight_data
  WHERE (l_where).

ENDFUNCTION.
```

In this way you can call function **`zsfli_sflight_getlist`** only with parameter **`p_fldate`** set, the select will filter and return all records for desired date.
  
~Enjoy

UPDATE2: I have added additional check for checking if there are already added `WHERE` conditions, so that we can combine several conditions at once:

```abap
IF l_where IS NOT INITIAL.
    APPEND &apos; and &apos; TO l_where.
ENDIF.
```</content:encoded></item><item><title>Get Ruby on Rails working on Ubuntu 11.10</title><link>https://blog.pnkv.de/post/2011/11/08/get-ruby-on-rails-working-on-ubuntu-11-10/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2011/11/08/get-ruby-on-rails-working-on-ubuntu-11-10/</guid><description>Handling Ruby On Rails installation issues.</description><pubDate>Tue, 08 Nov 2011 10:54:25 GMT</pubDate><content:encoded>A long time I have not been using Ruby On Rails. I have decided to give it a try again, so started by installing on Ubuntu 11.10 in VirtualBox. From what I remember - I have never happened before having issue with RoR working out of the box. Unfortunately this was not the case this time. Everything started with something really new to me:

```
    Invalid gemspec in [/var/lib/gems/1.8/specifications/json-1.6.1.gemspec]: invalid date format in specification: &quot;2011-09-18 00:00:00.000000000Z&quot;
    Invalid gemspec in [/var/lib/gems/1.8/specifications/tilt-1.3.3.gemspec]: invalid date format in specification: &quot;2011-08-25 00:00:00.000000000Z&quot;
```

At the beginning I have tried to solve it in several ways - by installing ruby from APT sources via

`sudo apt-get install rails`

or just by installing rails from gems:

`sudo gem install rails`

Both re-installation and methods did not worked.
  
So I have to dig deeper.
  
After a lot of searching in google I found a simple solution. Obviously gemspecs have some different date formats that don&apos;t validate. **So if you have such a message, just run the following command:**
  

`sudo sed -i &apos;s/ 00:00:00.000000000Z//&apos; /var/lib/gems/1.8/specifications/*`

This will fix the message. As soon as you install some new gem and you have this message - just run the script again.

Next it came the problem with **SQLIte3**:

```
    Building native extensions.  This could take a while...
    ERROR: Error installing sqlite3-ruby:
    ERROR: Failed to build gem native extension.
    /usr/bin/ruby1.8 extconf.rb
    checking for sqlite3.h... no
    sqlite3.h is missing. Try &apos;port install sqlite3 +universal&apos;
    or &apos;yum install sqlite3-devel&apos; and check your shared library search path (the
    location where your sqlite3 shared library is located).
    *** extconf.rb failed ***
    Could not create Makefile due to some reason, probably lack of
    necessary libraries and/or headers.  Check the mkmf.log file for more
    details.  You may need configuration options.

```

**This is solved by installing the development package of SQLite Ruby:**

```sh
sudo apt-get install libsqlite3-dev
```

And at the end it came the problem with **missing ExecJS engine**:

_``_ 

This I solved by downloading JavaScript engine from the URL mentioned (in my case Google V8) and putting on require in _config/boot.rb_

```
sudo gem install execjs
sudo gem install therubyracer
```

And adjust your applicaiton&apos;s **config/boot.rb**:

```ruby
require &apos;rubygems&apos;
require &apos;execjs&apos;
require &apos;v8&apos;

# Set up gems listed in the Gemfile.
ENV[&apos;BUNDLE_GEMFILE&apos;] ||= File.expand_path(&apos;../../Gemfile&apos;, __FILE__)

require &apos;bundler/setup&apos; if File.exists?(ENV[&apos;BUNDLE_GEMFILE&apos;])
```

After all these fixes, everything ran smooth.
  
I am sure there could be more elegant way to fix all these issues, so feel free to propose solutions.
  
~Enjoy</content:encoded></item><item><title>&apos;Preview&apos; crashes under Mac OSX Lion - FIX</title><link>https://blog.pnkv.de/post/2011/08/12/preview-crashes-under-mac-osx-lion/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2011/08/12/preview-crashes-under-mac-osx-lion/</guid><pubDate>Fri, 12 Aug 2011 22:10:28 GMT</pubDate><content:encoded>It happened, that when I upgraded to Lion, for some reason Preview stopped working. This was new to me - usually I don&apos;t expect such behavior under Mac OS. Seems that lots of people had this, especially the ones that have upgraded MBP with SDD and having HDD at the place of Optical Drive. In this case you make SymLinks in your home directory pointing to HHD for Downloads (for Photos, Music, Movies or anything that you can afford to play from slow media and takes more space, which is expensive on SSD).

The FIX: Remove the symlink for Downloads, start Preview, create symlink, start preview again:

```bash
killall -9 Preview
cd ~/
rm Downloads
open -a Preview
killall -9 Preview
ln -s YOUR_LINK_DIRECTORY_FOR_DOWNLOAD Downloads
open -a Preview
```

~Enjoy

UPDATE: The same happened with TextEdit - I suppose it will be for all programs that use one and the same IO with Downloads. So in case it happens, just replace `Preview` with</content:encoded></item><item><title>Solving Issues Like Warning Attempting to Create Use_block_in_frame Variable With Block That Isnt in the Frame</title><link>https://blog.pnkv.de/post/2011/08/01/solving-issues-like-warning-attempting-to-create-use_block_in_frame-variable-with-block-that-isnt-in-the-frame/</link><guid isPermaLink="true">https://blog.pnkv.de/post/2011/08/01/solving-issues-like-warning-attempting-to-create-use_block_in_frame-variable-with-block-that-isnt-in-the-frame/</guid><pubDate>Mon, 01 Aug 2011 22:42:59 GMT</pubDate><content:encoded>I used to fight for a while with strange issue. I am using Singleton in my iOS application to hold Session information. Unfortunately when using NSMutableArrayList to hold stack of current objects - the references become empty at some point and there is a warning like:

`warning: Attempting to create USE_BLOCK_IN_FRAME variable with block that isn&apos;t in the frame.`

While searching on the net - I have mentioned one comment about using singletons - well - this was my lead.
  
I am using common singleton macro that defines most of the memory management methods. Exactly in session manager I used the macro, before `@synthesize` - this was the problem, static definitions should not appear before synthesized methods. So if you have something like this, just replace it with:

```objc
@synthesize loggedUserId, ...
SYNTHESIZE_SINGLETON_FOR_CLASS(SessionManager)
```</content:encoded></item></channel></rss>