Month: February 2016

Get started with Polymer 1.0 and Sublime Text 3.0

In a previous post I have explained how to get started with Polymer 1.0 and Webstorm 11. Unfortunately WebStorm is a paid product and not all of my followers can purchase a license (me neither, I am trying to see if JetBrains will grant me a teacher license for free).

So, I decided to create a new tutorial which explains how to get started with Polymer 1.0 using Sublime Text, a power and free text editor also used by Google Polymer’s Team. In this tutorial I will use more tools than in the previous one because SublimeText is just a text editor (powerful but still a text editor), so in order to run your app you also need an integrated web server like GULP and other tools.

Download the necessary tools

First of all, in order to have the proper environment setup correctly, especially in Windows, you MUST download all tools before you start to download SublimeText or Polymer, otherwise you will start the nightmare of “path not found” errors and similar.

  • GIT
    GIT is a well-known command tool for managing GIT repositories. Even if you come from an SVN or TFS (Team Foundation Server) environment I would suggest you to get started on GIT because even companies like Microsoft are moving their source code into GitHub or BitBucket repositories and GIT is used by BOWER to download and synchronize components from Polymer.
    https://git-scm.com/
  • NODE.js
    Node is a JavaScript runtime build on Chrome V8 JavaScript engine. If you work with Polymer your primary use of Node is with the command NPM, which will be used in parallel with BOWER.
    https://nodejs.org/en/
  • BOWER
    If you come from Java you may be aware of “Maven Central” while if you come from .NET you may be aware of “Nuget”. Well BOWER is the same concept applied to web development. It allows you to download “packages” of CSS, JavaScript and HTML files packed as “components”. Without Node.js you can’t use BOWER because it requires the NPM (Node Package Manager) command tool.
    http://bower.io/

So at this point you have your core tools registered and working correctly. Now it’s time to download SublimeText 3.0 and configure it in order to get it setup correctly. The download link is available here: https://www.sublimetext.com/3

Configure Sublime Text 3.0

After Sublime Text is installed you need to configure it in order to understand Polymer 1.0 and in order to being able to run Polymer using GULP.

Step #01 – Sublime Package Manager

Sublime provides an integrated console where you can run Sublime commands. You can open the console using two different techniques:

  • CTRL + `
  • Menu > View > Show Console

When the console is open, copy the script that will enable package manager, which is available here.

Step #02 – Install Sublime Plugins

Sublime comes out of the box with almost anything but in order to create a proper development environment for Polymer 1.0 we need some plugins:

Tip: CTRL + SHIFT + P will open “Package Manager”

SNAGHTML12c1e91

Below is a list of plugins that I personally believe you should have installed in order to be able to work with Polymer

  • Install Package > Autoprefixer
    image

    If you want a quick way to add vendor prefixes to your CSS, you can do so with this handy plugin.
  • Install Package > Emmet
    image
    Add some useful keyboard shortcuts and snippets to your text editor.
  • Install Package > HTML-CSS-JS Prettify
    image
    This extension gives you a command to format your HTML, CSS and JS. You can even prettify your files whenever your save a file.
  • Install Package > Git Gutter
    image
    Add a marker in the gutter wherever there is a change made to a file.
  • Install Package > Gutter Color
    image
    Gutter Color shows you a small color sample next to your CSS.

Step #03 – Create a new Project

Finally, we need to create a Sublime Text project in order to keep all our files in a good structure. First of all you need a folder, in my case I work in “C:\DEV” and in this case I am going to have a project folder called “C:\DEV\Polymer_First” where I will save my project structure.

Open Sublime Text and point to the menu > Project > Save Project As:

image

This will create the new project with an extension of .sublime-project. Then go again into View Menu and choose Sidebar or simply press CTRL + K, CTRL + B.

Initialize Polymer

Now we can finally initialize our Polymer project.

Click on Project > Add Folder to Project and choose your root folder so that your workspace and project structure are pointing to your root project.

Open your SHELL or Command Prompt or TERMINAL and point to your Sublime Text root path, which is in my case “C:\DEV\Polymer_First” and type bower init:

image

Then download the basic setup for polymer using:

  • bower install –save Polymer/polymer#^1.2.0
  • bower install –save PolymerElements/iron-elements
  • bower install –save PolymerElements/paper-elements

At the end you should have this structure which includes the first .html filder (Index.html):

image

Final step, which is the one I love most, is to install Sublime Server, which is nothing more than a very simple Phyton local webserver.

CTRL + P > Install Package > Sublime Server

And voila’, now you can right click an .HTML file inside your Sublime Text editor and choose “View in Browser” which is by default http://localhost:8080.

Final Note
This is just an overview of how to setup Sublime Text but if you come from a complex IDE like Visual Studio or IntelliJ I would kindly suggest you to spend some time on Sublime and download all plugins that will make your life much easier. There are tons of useful plugins for web development and some specific for Polymer like the following:

… and many more

Polymer 1.0–Customize Style of existing components

Polymer 1.0 comes with plenty of available components, especially if you are going to implement Material Design. The only problem is that they implement the default style which usually doesn’t fit with mine.

In this post I want to show you multiple options of customizing a Polymer component together with the help of Polymer 1.0 documentation, available online.

Override the Style using <style>

Let’s start by preparing a Polymer project, like explained in my previous tutorial, and we add a simple Toolbar with two icons:

image

And this is my markup to import and create a Toolbar with two paper-icon-buttons:

<!-- Toolbar element -->
<link href="bower_components/paper-icon-button/paper-icon-button.html" rel="import">
<link href="bower_components/iron-icons/iron-icons.html" rel="import">
<link href="bower_components/paper-toolbar/paper-toolbar.html" rel="import">

<!-- Toolbar -->
<paper-toolbar>    <paper-icon-button icon="menu"></paper-icon-button>    <div class="title">My Toolbar</div>    <paper-icon-button icon="search"></paper-icon-button> </paper-toolbar>

Now, if I want to modify the background color of the Toolbar, first, I need to head to the paper-toolbar documentation here and find out how I can do that.
The CSS property that we want to override in our case is called –paper-toolbar-background.

Inside the HEAD tag of your page, you can create a new <style> tag and override the style globally by using the selector :root, like this example:

<head>

<!-- Override globally -->
<style is="custom-style">
:root{
--paper-toolbar-background: #FF6D00;
}
</style>
</head>

image

It is important to use the attribute is=”custom-style” which will inform Polymer that your style is going to override the normal Polymer CSS. Also, the tag style must be inside the <HEAD> tag otherwise it won’t work because it will be loaded too late by polymer.

Now, let’s say that this is too invasive for you and you want to override the toolbar background only for a specific scenario, for example, only for a certain webpage. We know that for the specific webpage the toolbar must be pink, so we can identify the toolbar id with a “pink” name:

<style is="custom-style">
:root{
--paper-toolbar-background: #FF6D00;
}

#pink-toolbar{
--paper-toolbar-background: #E91E63;
}
</style> <!-- Toolbar --> <paper-toolbar id="pink-toolbar">

With this statement you are going to have all toolbars in your project with a background color equals to #FF6D00 except the one with id equals to pink-toolbar which will have a background color equals to #e91e63.

image

Create a custom style component

Now, the best feature of Polymer is the capability of loading components, it is really helpful. Think about this, you have deployed an application which should be capable to load custom themes based on the user logged in, so what about having a custom CSS component which will override all your UX settings? Well with Polymer 1.0 this is possible and is quite straight forward.

First of all, we need to create a custom component which we will call “raf-theme” as following:

image

Then I am going to declare my DOM inside the page “raf-theme.html” as following:

<dom-module id="raf-theme">
<template>
<style>
:root{
--paper-toolbar-background: #FF6600;
}
</style>
</template>
<script>
Polymer({
is: "raf-theme"
});
</script>
</dom-module>

And now I can just use my custom theme as a normal Polymer component in the following way:

<head>
<!-- import the style -->
<link href="bower_components/raf-theme/raf-theme.html" rel="import">

<!-- use it -->
<style is="custom-style" include="raf-theme"></style>
</head>

In my own opinion, the best way is to have multiple dom-element into your “theme” component, one per each part of the UX. For example inside raf-theme I have the following elements:

  • raf-toolbar-theme
  • raf-drawer-theme
  • raf-form-theme

and so on and I declare each theme only when I need it, plus everything is modularize so for me it’s easier to find a specific CSS property of a specific component and override it.

Get started with Polymer 1.0 and WebStorm 11

So this year one of my goals is to learn Polymer 1.0. I followed this project for about a year now and I believe that the framework is mature enough to be adopted even into a production environment. Unfortunately Google didn’t make a great job regarding Polymer (in my own opinion) and there is not a great web development IDE available like they did with Android Studio for Android development.

In the past I worked a lot with Visual Studio but also with JetBrains tools and I found WebStorm a very reliable tool for web development, so I decided to start this article which will explain how to setup the correct development environment for Polymer 1.0 using WebStorm.

Note:
I have both Linux and Windows 10 PCs, I don’t use MAC at all, and this article is all based on my Windows configuration. If you are going to use WebStorm and Polymer on Linux the tutorial is still valid, but if you are on MAC, well you are on your own Winking smile

Download the necessary tools

First of all, in order to have the proper environment setup correctly, especially in Windows, you MUST download all tools before you start to download WebStorm or Polymer, otherwise you will start the nightmare of “path not found” errors and similar.

  • GIT
    GIT is a well-known command tool for managing GIT repositories. Even if you come from an SVN or TFS (Team Foundation Server) environment I would suggest you to get started on GIT because even companies like Microsoft are moving their source code into GitHub or BitBucket repositories and GIT is used by BOWER to download and synchronize components from Polymer.
    https://git-scm.com/
  • NODE.js
    Node is a JavaScript runtime build on Chrome V8 JavaScript engine. If you work with Polymer your primary use of Node is with the command NPM, which will be used in parallel with BOWER.
    https://nodejs.org/en/
  • BOWER
    If you come from Java you may be aware of “Maven Central” while if you come from .NET you may be aware of “Nuget”. Well BOWER is the same concept applied to web development. It allows you to download “packages” of CSS, JavaScript and HTML files packed as “components”. Without Node.js you can’t use BOWER because it requires the NPM (Node Package Manager) command tool.
    http://bower.io/

Now, after you install GIT, open your command prompt and type:

git --version
# and the output will be
git version 2.6.2.windows.1

If you don’t get so far it means that you don’t have the GIT bin folder registered as a Windows Environment Variable. The second step is to verify that node is installed and that’s the same of GIT, just type

npm version
# and the output will be
{ npm: '3.6.0',
  ares: '1.10.1-DEV',
  http_parser: '2.6.1',
  icu: '56.1',
  modules: '47',
  node: '5.6.0',
  openssl: '1.0.2f',
  uv: '1.8.0',
  v8: '4.6.85.31',
  zlib: '1.2.8' }

Great. Last step is to install the package BOWER from Node.

npm install -g bower

And then verify that bower is installed by typing:

bower --version

So now you are 100% sure that you can move forward and prepare your dev environment.

Install and Configure WebStorm

At the time I am writing this article WebStorm is available in the version 11. I assume that in the future nothing will change regarding this part of the setup, especially because all JetBrains IDE are based on the same core IntelliJ IDE. WebStorm can be downloaded here: https://www.jetbrains.com/webstorm/ and you can use it for 30 days, then you need to buy a license or apply for a free license.

After WebStorm is installed, open the IDE and choose “new empty project” and name it polymer_test like I did:

image

Now you should have an empty project and WebStorm ready to rock. If you look at the bottom of the IDE you will see a “Terminal” window. This is an instance of your DOS command prompt (in Windows) and your Terminal prompt (in Linux). Just double check that everything is fine by typing something like “bower –version” or “git –version”:

image

Step 01 – Init Bower

This is the basic of polymer which is needed in order to get started, you need to run the command “bower init” which will prepare a JSON file with the project configuration information. If you don’t know what to do here, just keep press ENTER until the json file is created.

image

Now you should have in your root a file named bower.json which contains your project’s configuration information.

Step 02 – Download the core of Polymer

Second step is to download the Polymer core. This is required by any Polymer project. type “bower install –save Polymer/polymer#^1.2.0” in order to download the latest stable version of Polymer which is the 1.2.0 version.
If you don’t specify the version, bower will download all available version and then ask you which version you want to use.

image

At this point your project will have a new folder called “bower_components” and the Polymer core component’s folders:

image

Final, create a new page and name it “index.html” with the following HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My First Polymer Application</title>
<script type="text/javascript" src="bower_components/webcomponentsjs/webcomponents.js"></script>
<link href="bower_components/polymer/polymer.html" rel="import">
</head>
<body>

</body>
</html>

Now your page is ready to be used as a Polymer page, you only need to import the components that you need or create your own ones. If you want to be sure that everything works as expected, just right click on your .html file and choose “browse with” and test it on your preferred browser (I assume Chrome):

image

Step 03 – Download the Material Design components

If you know already that you are going to work with Material Design components, then you can easily download the whole iron-components and paper-components into your project with two simple bower commands:

bower install --save PolymerElements/iron-elements
bower install --save PolymerElements/paper-elements

Then you can try to create your first page by importing, for example, the Material Design Toolbar components as following:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My First Polymer Application</title>
<script type="text/javascript" src="bower_components/webcomponentsjs/webcomponents.js"></script>
<link href="bower_components/polymer/polymer.html" rel="import">

<!-- Toolbar element -->
<link href="bower_components/paper-toolbar/paper-toolbar.html" rel="import">
</head>
<body>
<paper-toolbar>
<div class="title">My Toolbar</div>
</paper-toolbar>
</body>
</html>

And you should have a nice page with a basic Material Design Toolbar like mine:

image

Enjoy!

Enable Authentication in ElasticSearch

After you have configured your ElasticSearch endpoint, the next important step is to make it secure. If you have a standard installation of ElasticSearch probably you have your ES endpoint pointing to http://localhost:9200. In my case I do have this configuration and this is how I can query into a test index:

GET http://localhost:9200/test/persons/1 HTTP/1.1
User-Agent: Fiddler
Host: localhost:9200
Content-Length: 0

And ElasticSearch will return an HTTP Status 200 OK with my resultset:

HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Content-Length: 196

{"_index":"test","_type":"persons","_id":"1","_version":1,"found":true,"_source":{
   "first_name":"Raffaele",
   "last_name":"Garofalo",
   "city":"Izmir",
   "e_mail":"raffaeu@gmail.com"
}}

The major problem of the default installation of ES is that is totally unsecure.

  • First is running over an HTTP protocol, which means that all information sent are in clear text, including your authentication credentials 
  • Second, there is no authentication mechanism in place, which means that anybody can get the data from my endpoint

So let’s see how we can enable Authentication and how we can enable SSL to make our ES endpoint secure.

Enable Authentication with Shield

One of the features that I really love about ES is the plugin architecture. You can easily install on an existing ES endpoint any of the available plugins with a couple of lines of code and configure them at runtime.

One of the most important plugins available for ES is Shield. Shield is a plugin that provides plenty of options to secure your ES endpoint, just to mention few:

  • Enable Basic Authentication with Username and Password
  • Provide three different type of basic User [admin | power_user | guest]
  • Create custom roles with custom permissions
  • Enabling Message Authentication
  • Auditing
  • Custom authentication providers such as LDAP, OAuth, Active Directory and more

Note:
If you have multiple nodes for your cluster, in order to have Shield running correctly you must stop all nodes and install shield over all your nodes. This is the only option available so you must take offline your ES while installing Shield

In order to install Shield you should open an ElasticSearch SHELL, which in Windows means “open a DOS console and point to your /bin folder where the elasticsearch program is available”:

# browse the elastic search dir
$ CD C:\Program Files\elasticsearch-2.1.1\bin

Then you have to install two plugins, License and Shield. This is required because Shield is partially free, which means that:

When your license expires, Shield operates in a degraded mode where access to the Elasticsearch cluster health, cluster stats, and index stats APIs is blocked. Shield keeps on protecting your cluster, but you won’t be able to monitor its operation until you update your license. For more information, see License Expiration.

$ plugin install license
$ plugin install shield

Until you reboot your ES endpoint, you will not be able to have the Authentication enabled. After reboot, if you try to issue the previous request, you will get an HTTP 401 UNHAUTORIZED response:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="shield"
Content-Type: application/json; charset=UTF-8
Content-Length: 357

{"error":{"root_cause":[{"type":"security_exception","reason":"missing authentication token for REST request [/test/persons/1]","header":{"WWW-Authenticate":"Basic realm=\"shield\""}}],"type":"security_exception","reason":"missing authentication token for REST request [/test/persons/1]","header":{"WWW-Authenticate":"Basic realm=\"shield\""}},"status":401}

So the next step is to create an Admin user that we can use to start to query our ES endpoint:

#browse /bin/shield directory
$ esusers useradd es_admin -r admin

With the esusers useradd command we created a new user named es_admin with the param –r we defined the role admin (available roles are admin, power_user, guest).

Second step, we need to issue an authenticated request to ES using our account in the following way:

GET http://localhost:9200/test/persons/1 HTTP/1.1
User-Agent: Fiddler
Host: localhost:9200
Content-Length: 0
Authorization: Basic ZXNfYWRtaW46c2VjcmV0

Where the “strange” string is just username : password combination, converted by Fiddler in a 64 bit string.

All right, so now you have your ES secured and the basic user management in place but you have another problem. Now you are sending per each request a username and password over the web, so you must enable SSL communication on your ES endpoint to encrypt the communication.

Note:
If you want to create custom roles with custom access, you need to modify the file [elasticsearch]/config/shield/roles.yml. In this file you can have a look at the current roles [admin, power_user, user] and modify them or create new one. For example you may have a role that grant permissions only to a specific index (see multi-tenant architecture).
Remember, every time you modify a configuration file in ES you MUST restart the service otherwise ES will keep using the cached .yml configuration files.

Enable SSL on ElasticSearch

First of all you need a X.509 certificate for your domain. There is no shortcut here, if you have a domain where you host your ES endpoint you must purchase an SSL certificate from a CA authority that covers your domain. This procedure is a bit painful and verbose but when done it’s done for your entire ES installation. You can also create a cert file from your own Windows/Linux machine, for example, using OPENSSL or similar but remember that your certification file will not be signed by a known CA authority and you may encounter problems during production.

In my case I host ES in a public DNS and I have a Domain Certificate from a CA authority in the form of .pfx file. Using OPENSSL I create a new .pem file from my .pfx using this command:

openssl pkcs12 -in certificate.pfx -out certificate.pem -nodes

Anyway you must have access to a .pem certificate file in order to continue.

keytool -importcert -keystore node01.jks -file cacert.pem -alias my_ca

This command (keytool) will import the certificate into the Java Keystore Database, which contains a list of trusted certificates.

Next you need to generate a private key and a certificate for your node as following:

keytool -genkey -alias node01 -keystore node01.jks -keyalg RSA -keysize 2048 -validity 712 -ext san=dns:node01.example.com,ip:192.168.1.1

With this command we create a key and a public certificate valid for 712 days (which is the classic example shown on ElasticSearch documentation). This command will also prompt you for some questions that will be registered together with the certificate. The san attribute allows to specify the DOMAIN where you are hosting your ES endpoint.

So, right now you have a node’s certificate but it needs to be signed by a CA authority, actually the one who issued the certificate for you.

keytool -certreq -alias node01 -keystore node01.jks -file node01.csr -keyalg rsa -ext san=dns:node01.example.com,ip:192.168.1.1

Now we have a Certificate Signing Request .csr that we can send to our CA. The CA will sign it and returns to you a .crt file. You can also use OPENSSL and generate the .crt by yourself if you wish. At this point you have to import the .crt into your .jks database with the following command:

keytool -importcert -keystore node01.jks -file node01-signed.crt -alias node01

Now we can configure SHIELD to use SSL and HTTPS transport protocol. Just let ES knows where your keystore is located and which is the password for your keystore and for your certificate:

# ---------------------------------- SSL -----------------------------------
shield.ssl.keystore.path: C:\Program Files\elasticsearch-2.2.0\elasticsearch-2.2.0\config\cert\keystore.jks
shield.ssl.keystore.password: [keystore password]
shield.ssl.keystore.key_password: [certificate password]
shield.transport.ssl: true
shield.http.ssl: true

At this point your Elastic Search will be hosted still on port 9200 (if you didn’t override this setting) but available only over HTTPS.

Alternative way of creating a keystore

In my specific scenario I didn’t want to modify the certificate because my CA authority is quite strict so I didn’t have the option to import a .pem, modify and create a .csr and so on so I used an alternative way.

First of all I have created my keystore:

keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.jks -keysize 2048

Then I have imported by .pfx file as is, without any modification:

keytool -importkeystore -srckeystore mypfxfile.pfx -srcstoretype pkcs12 
-destkeystore keystore.jks -deststoretype JKS

Then I created a .csr request for my DNS but I will not send the request to my CA authority:

keytool -certreq -alias mydomain -keystore keystore.jks -file mydomain.csr

And finally I moved the two files, .jks and .csr into the config directory of elastic search and configured elastic search using the keystore password and the original certificate password. It worked like a charm and I didn’t need to send a .csr and import a .crt.