23 Aug 2016, 23:30

Export Certificate and Private key from JKS

I had to migrate web application written in Java to NodesJS,

Java web containers store certificates inside JKS Keystore where NodeJS requires certificate and private key in PEM format.

Exporting certificate directly from JKS is easy by using keytool, but exporting private key is not allowed, To export the private key using Java, we need to interact with the keystore by writing some custom code using the Keystore java API,

the other alternative is simply convert the JKS into a PKCS12 and export the certificate & key using openssl

Convert JKS to PKCS12 format:

keytool -importkeystore -srckeystore mykeystore.jks -destkeystore mykeystore.p12 -deststoretype PKCS12

Note: The -importkeystore parameter is only supported with the keytool that ships with Java ver 1.6+

you can view the content of the pkcs12 keystore by:

openssl pkcs12 -in mykeystore.p12

(Specifically look for the friendlyName that corresponds to the alias property of in JKS)

Export the certificate:

openssl pkcs12 -in mykeystore.p12 -nokeys -out cert.pem

Export the private key (unencrypted)

openssl pkcs12 -in mykeystore.p12  -nodes -nocerts -out key.pem

the -nodes means “No DES”, that is “do not encrypt the private key that will be exported to key.pem”

Make sure you keep the private key safe (recommended: chmod 600 key.pem)

23 Aug 2016, 22:43

Migrate Octopress to Hugo

My blog was based on Octopress blogging system, based on jekyll, but I was never a ruby person, it also seems like Octopress is not so active lately,

In the other hand, Hugo feels super slim and simple, thanks to Go and Hugo, it takes only few lines to start a blog,

You can download a binary package of Hugo, but I have Go installed so it’s simply 1 command:

go get -u -v github.com/spf13/hugo

Creating a new blog is simply one command:

hugo new site myblog

This command creates the myblog folder with some initial data that serves as a baseline for our blog.

Adding a new post is simple as:

hugo new post/welcome.md

This generates the content/post/welcome.md file, a post is just a simple file, no magic!

A theme defines how the blog look like visually, there are many themes, choose the one you like, in this post, I use the purehugo theme because it’s clean and simple.

cd themes
git clone https://github.com/dplesca/purehugo.git

Lets star a local server to see our shining new blog:

hugo server --theme=hugo_theme_robust --buildDrafts

Hit in browser: http://localhost:1313

You should see the welcome blog entry we just added.

Migrate from Octopress

Hugo has a built in support to migrate from jekyll

cd my_octopress_blog
ls
config.yaml ... source/ ...
hugo import jekyll source/ hugo-import/
Congratulations! 26 post(s) imported!
...

Make sure to have config.yaml and the source folder in current directory, running the import command should import all files

Simply move the posts folder into your new blog content folder by:

mv hugo-import/content/post/* <location_of_new_hugo_blog>/content/post`

Happy blogging!

14 Sep 2015, 00:00

Default function options stash with ES6 destructuring assignment.

ES6 opens up a clean approach to define function options stash thanks to the destructuring assignment syntax,

Assuming we want options but let the user overrides it, we can declare our function that way:

function hello(param1, {debug = true, whatever = false} = {}) { }

The advantages are, clearly there is no code in the body function to achieve default options & user overrides.

13 Sep 2015, 00:00

Add additional properties to a result of a function or a fucntion map using ES6 spread operator.

Sometimes it makes sense to add additional properties to a result of a function,

Examples could be enhancing an operation result with some meta data, extending with a timestamp, run time, etc,

Using ES6, we could easily achieve this by:

bindData(oper, props) {
  if (typeof oper === 'function') {
    return (...args) => ({
      ...oper(...args),
      ...props
    });
  }
  if (typeof oper === 'object') {
    return Object.keys(oper).reduce((prev, key) => ({
      ...prev,
      [key]: bindData(oper[key], props)
    }), {});
  }
  return oper;
}

Here are some clarifications:

  1. If oper is a function, we decorate the original function by a closure, return (...args) is the closure (read more about the spread operator.

In general, myFunction(...args); is equelevent to (args) { oper.apply(null, args); },

  1. When the returned function is invoked, the result of the original function ...oper(...args) is then merged with the props object, in other words:

...oper(), ...props is equelevent to: Object.assign({}, oper(), props); Read more about Object.assign

  1. If oper is an object, we bind each of its key’s recursively (assuming each property is a function).

05 Sep 2015, 00:00

ES6, React & Browserify

ES6, React & Browserify

Browserify is a lightweight build tool for JS, you can start ‘require’ modules with zero configuration, Thanks to Babelify, you can start writing ES6 code (via Babel) write away,

Here’s a proof how simple it is,

Lets create a package.json file and install minimal dependencies

npm init
npm install --save react
npm install --save-dev browserify babelify watchify

Lets give Browserify a hint that it should perform code transformation via babelify by adding this json tag to package.json

"browserify": {
  "transform": [
    "babelify"
  ]
}

It can also be nice to just type npm start when developing, so lets add a start script to package.json as well

“start”: “watchify –extension=js -o bundle.js index.js & python -m SimpleHTTPServer”,

Note: Watchify is not mandatory but it’s great tool for watching your code changes and auto rebuild when a change gets discovered.

Lets put the simplest index file ever:

<html>
  <body>
    <script type="text/javascript" src="bundle.js"></script>
  </body>
</html>

Here’s a simple ES6 class with React.

import React from 'react';

class Hello extends React.Component {
  constructor(props) {
    super(props)
    this.state = {count: props.initCount}
    this.tick = this.tick.bind(this)
  }

  tick () {
    this.setState({count: this.state.count + 1});
  }
  render(){
    let { name } = this.props
    let { count } = this.state
    return (
      <button onClick={this.tick}>Hello {name} {count}</button>
    );
  }
}

React.render(<Hello name="Stranger" initCount={5}/>, document.body)

Running the code:

npm start

Open browser http://localhost:8000

To summary:

1) Browserify is lightweight build tool, it handles modularity by understanding require 2) Labelify is a plugin for Browserify, it takes care of transpilling ES6 code to ES5 via Babel. 3) Thanks to Babel & React integration, there’s no need for any extra plugins to perform JSX transformations.

23 Jun 2015, 00:00

Extending behavior of React Components by ES6 Decorators & Higher Order Components

About Mixins & Higher Order Components

Sometimes it makes sense to extends a behavior of a component, while mixins are still alive, they’r not recommended anylonger, use Higher Order Components instead.

So instead of doing this:

function StoreMixin(...stores) {
  var Mixin = {
    getInitialState() {
      return this.getStateFromStores(this.props);
    },
    ...
  }
}

var UserProfilePage = React.createClass({
  mixins: [StoreMixin(UserStore)],
  propTypes: {
    userId: PropTypes.number.isRequired
  },
  ...
})

You can do that:

function connectToStores(Component, stores, getStateFromStores) {
  const StoreConnection = React.createClass({
    getInitialState() {
      return getStateFromStores(this.props);
    },
    ...
    render() {
      return <Component {...this.props} {...this.state} />;
    }
  })
}

We just wrap the component and passes some additional props to it, it is a clean and generic solution for extending components without merging behaviors being implemented by React’s mixin merge logic.

You can read more about Higher Order Components here

Extending via ES6 Decorators

Sometimes it makes sense to extends a component without the need to wrap it manually, this technique is common in different frameworks to define components less verbosely when extra functionality is demanded.

Here is a short example how it works, Lets extends the context of our component hierarchy with a print function, so we use it in our render method:

class MyPage extends Component {
    static contextTypes = contextTypes;
    render() {
        return(
            <div>{this.context.print('Hello World')}</div>
        )
    }
}

Assuming MyPage is a child component of App, here is how our App component looks like:

var contextTypes = {
    print: PropTypes.func.isRequired
}

var myContext = {
    print: (m) => (m)
}

@context(contextTypes, myContext)
export default class App extends Component {
    render() {
        return (
            <MyPage/>
        )
    }
}

And here is the code of the decorator:

export default function context(contextTypes, context) {

    return function (DecoratedComponent) {
        return class {
            static childContextTypes = contextTypes;
            getChildContext() {
              return context;
            }
            render() {
              return (
                <DecoratedComponent {...this.props} />
              );
            }
        }
    }
}

The Decorator expects an expression and invokes the function with the given parameters and must return a function that expects the annotated component as a parameter, then we just return a class with some context the wraps our component.

You can read more about Decorators here.

19 Jun 2015, 00:00

Elegant way to use React with ES6/ES7 features.

React, JSX, ES6.

So you want React, JSX the markup and write ES6/7 code style, but setting a working environment may be pain in the ass,

More to say, Facebook announced that its JSTransformer and react-tools going to be deprecated,

It seems like it’s starting to get confusing how to set a full working environment with JSX transformation and ES6/ES7 support.

While React 0.13.0-beta-1 announced great support for ES6, it still unclear how to build a full working environment that supports ES6 either,

You can find multiple boilerplate projects at github using WebPack, Browserify and other module loader tools available nowadays but I found all of them unclean, full of build scripts and things that just make things more complicated,

After doing some research, I feel like the best approach would be to go with JSPM repository that is based on SystemJs dynamic module loader.

The chosen tools:

  1. SytemJs - It is a Universal dynamic module loader, it supports AMD, CommonJS but the best of it is its native support for ES6 modules, with native support for Babel as its transpiler to ES5, it also uses JSPM which supports NPM and Github repos such as Bower does, so you can enjoy packages from both worlds.
  2. Babel as the ES6 transpiler, this transpiler is responsible to translate ES6 coding to ES5 as ES6 is not supported yet by most browsers, Babel is also supported by Facebook and provides JSX native transformation.

Enough said, here’s some code, we’ll start with empty folder!

Setting a clean working environment

Pre requisites

Lets install pre requisites:

npm install -g jspm
npm install -g http-server

Initializing Project

Create an empty folder and run

jspm init

You can choose default answers for all questions if not sure,

This will create a package.json and a config.js file required for SystemJs to work properly.

Now lets tweak config.js a bit to support ES7 so you can enjoy ES7+ property initializers and other ES7 cool features

"babelOptions": {
  blacklist: [],
  stage: 0,
  "optional": [
    "runtime"
  ]
},

blacklist: [] tells Babel not to ignore JSX transformation as by default it’s disabled, stage: 0 tells Babel that we want to use experimental ES7 syntax.

Creating an index.html file

Lets create our index file as every web app that respect itself has one!

Simply create index.html in the root folder with your favorite editor

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Title Here</title>
    </head>
    <body>
        <!-- build:js -->
        <script src="jspm_packages/system.js"></script>
        <script src="config.js"></script>
        <script>
            System.import('app/main');
        </script>
        <!-- endbuild -->
    </body>
</html>

See how clean and elegant is it? we just load system.js as our dynamic module loader and the generated config.js that holds our SystemJs configuration.

Then we import app/main as our first ES6 module that serves the application.

Create a simple React based class.

Thanks to SystemJs, we can now fully write application modules, lets create our main application entry point

Create a file app/main.js with the following content:

import React from 'react';
import App from './app';

React.render(<App/>, document.body);

This just import React and renders our App component.

Her eis the app/app.js file content:

import React from 'react';
var {Component} = React;

export default class MyApp extends Component {
    static propTypes = {
       flux: React.PropTypes.object.isRequired
   }

    render () {
        return (
            <div>Hello</div>
        )
    }
}

Now run http-server in your folder,

hitting http://localhost:8080 should display Hello :)

Summary

The combination of React, JSX transformation via Babel, and ES6/7 support via SystemJS provides a great clean and elegant way to write React code without the overhead of build systems and ugly scripts around.

01 May 2015, 00:00

Facebook React - simplified work flow.

React is a really game changer in the world of web development, As most web frameworks (such Angular, Ember, etc) supports two way bindings that really simplifies development life, when applications start to get bigger things start to get clashed as multiple views may be bound to multiple models and getting unexpected behaviors is not something imaginary,

React solve these problems by exposing a new flow that is based on unidirectional binding, combined with the usage of virtual DOM, DOM reconciliation should result a better performance than two way bindings based frameworks, Well, if Facebook uses it, then it scales :)

You can read about it in React’s web site, especially the Tutorial should give you a great starting point,

Watch out my next post about how to setup a React environment using great tools that will simplify your development lifecycle.

09 Feb 2015, 00:00

Hello world using Ratpack.

About Ratpack

Ratpack is a set of Java libraries that facilitate fast, efficient, evolvable and well tested HTTP applications built on Netty event driven networking engine,

After crawling into its source code, I find it simple and easy to use and it feels right, why? because:

  1. It’s super simple, its core has very limited number of dependencies
  2. Has out of the box extensions such as Guice, Jackson, etc, but nothing dictates you using them thanks to Guice modular architecture.
  3. Compatible with Java8 lambda syntax
  4. Testing is very easy.

Code can be written in Groovy or Java, and since java8 lambda syntax is so pretty, I find it suitable for the Ratpack handlers architecture quit well.

So here’s a simple hello world using Ratpack and Java8,

The build file (Gradle)

While used to Maven, It feels like Ratpack folks like Gradle, so I said why not use it?

Here’s a simple build.gradle file:

buildscript {
  repositories {
    jcenter()
  }
  dependencies {
    classpath "io.ratpack:ratpack-gradle:0.9.13"
  }
}

apply plugin: "io.ratpack.ratpack-java"
apply plugin: "idea"

dependencies {
  //Ratpack uses slf4j for logging
  runtime "org.slf4j:slf4j-simple:1.7.5"
}

//we need this since 0.9.13 is based on snapshot version of Netty
repositories {
  jcenter()
    maven {
      url "http://clinker.netty.io/nexus/content/repositories/snapshots"
    }
}

Create basic directories

mkdir -p src/main/java
mkdir -p src/ratpack

Run in the command like gradle idea to create Intellij project:

gradle idea

One of the things I mostly like about Ratpack is that it has no real notion of a “container”, you can simply start it a plain main method just like that:

import ratpack.server.RatpackServer;
import ratpack.server.ServerConfig;

/**
 */
public class Server {
    public static void main(String[] args) throws Exception {
        RatpackServer server = RatpackServer.of(b -> b
                        .serverConfig(ServerConfig.embedded()) //default config
                        .registryOf(r -> r.add(String.class, "world"))  // registry of supporting objects - optional
                        .handlers(chain -> chain                    // request handlers - required
                                        .get("hello", ctx -> ctx.render(ctx.get(String.class) + " !"))
                        )
        );

        server.start();
    }
}

Server will start with on some available port and will print: Ratpack started for http://localhost:65478

now hit in the browser http://localhost:65478/hello ! :)

01 Feb 2015, 00:00

Choosing Java Backend framework in 2015.

So it’s year 2015 and I’m taking a role in a new cloud service, helping to choose the right backend technology,

This is the summary of our requirements:

  1. Can quickly come up with some POC.
  2. HTTP driven.
  3. Native support for Async.
  4. Modular.
  5. Avoid frameworks that dictates specific code structure.

Here are few options we tried but decided to pivot and seek for alternatives,

Akka

Akka seems very promising, it feels lightweight, highly concurrent and distributed, Akka is based on actors pattern, an old pattern invented by Carl Hewitt and friends, promoted lately by Erlang,

We tried to create a POC with Akka, in conjuction with their new Akka Streams (which seems to replace Spray), both felt like a complete solution, but we decided to pivot out of it, I think I can summarize it in one sentence.

Although Akka seems to have support for Java, it’s just not a java project, Akka is written in Scala, and exposes Java APIs via bindings layers, I felt like its community is Scala oriented debugging code of Scala is something tough for people that plans to stick in the Java domain.

Vert.x

Vert.x is similar to NodeJs, written in Java, It is Netty based and works in a non blocking mode,

Vertx 3 seems to be very promising we found some advantages of it,

  1. We quickly could create a web app using Apex.
  2. Almost no configuration and deployment code is required to see real results.
  3. Completely written in Java (which was a big releaf after Akka)
  4. Scale out by levaraging an internal even bus.

But we decided to pivot again, but why?! because Vert.x makes certain irreversible decisions about how applications should be written, and working with the event bus was a nightmare, we tried to use Vertx Service Factory which eliminates most of the boilerplate code required to perform actions over the event bus, but it restrictions of passing only JsonObject and JsonArray frustrated us, We found ourself spending too much time on convertions between Vertx’s JsonObjects and application / core services models.

What now?

So what now? we’r still seeking for a better solution that hopefully will satisfy our needs.