Javascript: Generate a GUID

How to create a GUID in Javascript

Two years ago, I needed to generate GUID for an ExtJS project (purpose was to create on-the-fly a unique id for tchat messages user was sending). Hereafter the function I used (source should by StackOverFlow and other forums, I dont’ remember exactly), still working.

generateGUID : function() {
  return ((typeof(window.crypto) != 'undefined' 
      && typeof(window.crypto.getRandomValues) != 'undefined') 
    ? function() { // If we have a cryptographically secure PRNG
        var buf = new Uint16Array(8);
        window.crypto.getRandomValues(buf);
        var S4 = function(num) {
          var ret = num.toString(16);
          while(ret.length < 4){ ret = "0"+ret; }
          return ret;
        };
        return (S4(buf[0])+S4(buf[1])+"-"
            +S4(buf[2])+"-"+S4(buf[3])+"-"
            +S4(buf[4])+"-"+S4(buf[5])+S4(buf[6])+S4(buf[7]));
      }
    : function() { // Otherwise, just use Math.random
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
                .replace(
                        /[xy]/g, 
                        function(c) {
                          var r = Math.random()*16|0,
                              v = c == 'x' ? r : (r&0x3|0x8);
                          return v.toString(16);
                        }
                ); // replace
      }
   )(); 
}// generateGUID

Couple of references:

EJB: Inject a Singleton with @Startup

Introduction

Keywords

a @Singleton with @Startup bean. Example:

@Startup
@Singleton
class StartupClass {
  public void myPublicMethod() { 
    // do something
  }
  @PostConstruct
  void onStart() { }

  @PreDestroy
  void onStop() { }
}

Problem

with @Inject, I got a Wildfly dependency error:

"WELD-001408: Unsatisfied dependencies for type ..."

How to solve it?

Common

Create an interface with @Local over @Singleton class

// Interface ...
@Local
interface StartupLocalInterface {
  public void myPublicMethod();
}

Declare the interface

@Startup
@Singleton
class StartupClass implements StartupLocalInterface {
  public void myPublicMethod() { 
    // do something
  }
  @PostConstruct
  void onStart() { }

  @PreDestroy
  void onStop() { }
}

1st approach

  1. see Common aboce
  2. @Inject the interface
    @Stateless
    public class MyBean {
      // ...
      @Inject
      StartupLocalInterface startupClass;
      // ...
    }
    

2nd approach

  1. see Common above
  2. On top of class StartupClass, add an @EJB declaration:
     @EJB(name="startupClass", beanInterface=StartupLocalInterface.class)
  3. use a context lookup
    try {
        Context ctx = new InitialContext();
        StartupLocalInterface t = 
          (StartupLocalInterface) ctx.lookup("java:comp/env/startupClass");
        // do the job...
    } catch (NamingException e) {
        e.printStackTrace();
    }

ExtJS 5/6 : Alert Message (kind of Android Toast/Bootstrap Alert)

In ExtJS KitchenSink example, Sencha provides/uses an alert message, sliding from top, then sliding out.

This kind of temporary message is always useful to popup some alerts/informations for example.

After having a look on Sencha Ext.example.msg, I made couple of improvements using Bootstrap 3.x alert’s ideas.

So, this “temporay message box” slides from top, stays “delays” seconds, then slides out. There are 5 different classes (default, success, info, danger, warning) like in Bootstrap alerts (color are roughly identical). Here is a look of each:

ExtJS Alert/Toast messages with different classes
ExtJS Alert/Toast messages with different classes

The code (js and scss) is available on GitHub: My GitHub Repo

ExtJS 5/6 : Grid’s RowEditing Locale & Options

Within a Grid, RowEditing plugin is convenient to edit values directly. However, Locale (l10n, i18n) is  (sometimes) a mess with ExtJS 5 or 6, and that’s still the case with RowEditing.

However, one very simple way to solve this is to override button labels/messages while declaring/configuring the plugin:

Ext.define('MyApp.view.DataGrid',{
    extend: 'Ext.grid.Panel'
    ,requires: [
        'Ext.grid.plugin.RowEditing'
    ]
    ,plugins: [
        {
            ptype: 'rowediting',
            clicksToEdit: 2,  
            disabled: false, // disable RowEditing, tgrough binding for example
            saveBtnText: i18n('global.update'), // label for update/save btn
            cancelBtnText: i18n('global.cancel') // label for cancel btn
            errorsText: 'Errors', // errors text dirtyText: 'You need to commit or cancel...' // if record is dirty 
         } 
    ] /* ... */ });

And that’s all !!!  You could notice that I also declare “disabled” field as I bind it to enable/disable RowEditing plugin on the fly (for example, based on user profile).

For example, in the following screenshot, buttons are in french:

ExtJS Grid Row Editing in French
ExtJS Grid Row Editing in French

Memo : Nginx proxy for Wildly

Introduction

Quick setup of Nginx to have redirection on Wildfly instance based on uri path

Setup

Edit your server configuration file within

/etc/nginx/sites-available

Change “location” section to (for example):

        location / {
                # wildfly redirect
                location /app {
                        proxy_set_header   X-Real-IP $remote_addr;
                        proxy_set_header   Host      $http_host;
                        proxy_pass http://127.0.0.1:8080;
                        proxy_redirect http://127.0.0.1:8080 http://www.example.com;
                }
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

Here, only path starting with /app will be fully redirected to WildFly, i.e. your main  Application.java path should be @Path(“/app”).

ExtJS 6 – Router improvements

Introduction

With ExtJS 5.x, I was not convinced by the “Router” part of the framework. It was quite a mess, and implemented through Mixins. I remembered having a deep look on Saki example.

In ExtJS 6, the Router implementation is really a good step ahead, and remembers me the one I used in AngularJs. Sencha has made a detailed article over there.

Quick Summary

  1. Put the default route in your Application declaration. Example:
    defaultToken : 'home', // default route
  2. Defined routes with your Controller :
    routes : { 
      'users': 'onUsers',
      'user/:id' : 'onUser'
    },
    onUsers : function() {
      //...
    }
    onUser : function(id) {
      //...
    }
  3. Update/Change route within Controller (here “this” is the controller)
    this.redirectTo('user/1234', true); // redirect

You can also setup some masks on route parameters and have BeforeRoute function (see Sencha doc for more details).

Multiple Routes

Finally, one point : ExtJs 6 supports multiple routes (routes pipe), with a route separator “|” (which could be changed): in that case, each route is handled sequentially by its order of appearance.

Reference: Sencha’s ExtJS 6 : Router

Conclusion

In ExtJS 6, Router is in line with AngularJS’ one and is a big step ahead since ExtJS5.x.

ExtJS : Accessing Application from anywhere

In ExtJS, “Application” is handling and containing a lot of stuff. Among other things, useful getters are:

  • getStore(‘store_name’) : retrieve a store
  • getRoutes()  : get Routes

How to retrieve current Application?

In fact, is is really simple. Let’s imagine that your App namespace is ‘MyApp’; then it can be retrieve using:

MyApp.getApplication()

Update (March 13th): you can also use

MyApp.app

ExtJS 5/6 : localization / i18n / l10n

 

This post is an update of previous one : https://abarre.wordpress.com/2015/09/29/extjs-5-and-localization/

Project files are now hosted on GitHub : GitHub “extjs-i8n-lang” Project

Approach

This approach is very simple:

  1. Create a ‘Lang’ class
  2. Add languages string based on a ‘yaml/json’ tree approach
  3. Create some shortcuts
  4. Add you ‘Lang’ class in ExtJS’s Application requires section
  5. Use it

The ‘Lang’ class template

Ext.define('Lang',{
    singleton : true

    ,config : {
        currentLang : null,
        defaultLang : 'us'
    }

    ,getStrings: function(lang) {
        if (!lang || !Ext.isDefined(this.strings[lang]))
            lang=this.getDefaultLang();
        if (Ext.isString(this.strings[lang])) // got an aliase
            lang = this.strings[lang];
        return Ext.isDefined(this.strings[lang])
                ? this.strings[lang]
                : { };
    }

    ,t : function(label, lang) {
        var path = label.toLowerCase().split('.'),
            p = this.getStrings(lang); // strings
        for (var i = 0; i<path.length; i++) {
            if (Ext.isDefined( p[ path[i] ]))
                p = p[ path[i] ];
            else return '<<' + label + '>>';
        }
        return p;
    }

    ,constructor : function(config) {
        this.initConfig(config);
        if (!this.getCurrentLang())
            this.setCurrentLang( this.getDefaultLang());
    }

    strings: {
        'us_US': {
            'hello_world': 'Hello World!',
            'map' : 'Map'
        },
        'fr_FR': {
            'hello_world': 'Bonjour Le Monde!',
            'map' : 'Carte'
        },
        'es_ES': {
            'hello_world': 'Ola el Mundo!',
            'map' : 'Carto.'
        }
    }
});
var i18n = function(label, lang) { return Lang.t(label, lang); };

Usage

i18n('hello_world')
i18n('map')

Wildfly – PostgreSQL Driver Install

  1. Environnement:
    • Wildfly 10
    • Java JDK 8.xx
    • Postgresql 9.4
  2. Download Postgresql driver. See: https://jdbc.postgresql.org/download.html
  3. Run ./jboss-cli.sh from wildfly/bin
  4. From jboss-cli command-line:
    connect
    
    #add module
    module add --name=org.postgres --resources=/tmp/postgresql-9.4.1207.jar --dependencies=javax.api,javax.transaction.api
    
    # add driver to subsystem datasources
    /subsystem=datasources/jdbc-driver=postgres:add(driver-name="postgres",driver-module-name="org.postgres",driver-class-name=org.postgresql.Driver)
    
    # declare datasource: here: server is on localhost, and db is postgres_db
    # username is postgres and password is posgres
    data-source add --jndi-name=java:jboss/datasources/PostGreDS --name=PostgrePool --connection-url=jdbc:postgresql://localhost/postgres_db --driver-name=postgres --user-name=postgres --password=postgres