ExtJS 5/6 : FileField/FileUploadFile : reading data

Introduction

I have a “filefield” or “fileuploadfield” in ExtJS, and I’d like to read directly its content directly into the browser, when user selects a file.

It is useful when you’d like to display an image for example, as soon as the user selects it.

How To Proceed

First of all, you need to declare the “filefield” with a listener on “change” event. For example:

{
    xtype: 'filefield'
    ,fieldLabel: "File: "
    ,labelWidth: 70
    ,anchor: '100%'
    ,buttonOnly: true // hide text field below button
    ,buttonText: "Select a picture"
    ,listeners: {
        'change':  'onMediaChange'
    }
}

and in the Controller, the handler:

onMediaChange: function(widget, value, eOpts ) {
  var files = event.target.files
      self = this; // the controller
  if (!files || files.length == 0) return; // make sure we got something
  // Let's read content as file
  var reader = new FileReader();
  reader.onload = function (e) {
    // image content is in e.target.result
    // we can then put it into img.src, for example
    self.lookupReference('myImg').setSrc(e.target.result);
  };
  reader.readAsDataURL(files[0]);
}

and that’s it!

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

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 : 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

Getting Started: EJB/Persistence (with PostgreSQL)

[DRAFT… To be continued …] last update: Feb 4th

I’ve been using PHP (especially Symfony 2.x) for quite a while in my web projects (both backend and frontend), coupled with MongoDB.

Almost a year ago, I’ve discovered that PostGreSQL supports “JSON/JSONB” and handles “requests” over Json/JsonB. Couple of months ago, I had a project involving OptaPlanner, so I had to move to J2EE world, and it not so worst.

A month ago, I started a project (on my free time) from scratch to deeply evaluate pros/cons of EJB/JPA/… with Wildfly 9.x.

So here, I will not discuss pros/cons neither compare it with PHP Symphony,  Python Django, or even Ruby on Rails; just give couple of Tips/Tricks around “Getting Started”

  1. Install : PostgreSQL & Wildfly
    – For my PoC/testing (Wildfly+Postgresql) server, I use a VPS (see OVH VPS for example: 1 Go RAM, 128Mo SWAP, 10Go HD)
    – Install Java on your server
    – Install PostgreSQL (9.4 or above) and starts it
    – Download Wildfly, uncompress, and runs it (here in standalone mode, listening all interfaces).

    bin/standalone.sh -b=0.0.0.0

  2. Configure WildFly DataSource
    This is a critical path: configure WildFly datasources. By default, an “ExampleDS”, using H2 memory database, is configured.
    Have a look over here (quick tutorial).
    There are plenty of ways to configured a PostgreSQL datasource using WildFly Web Administration, command-line client or simply “standalone.xml” edit.
  3. Setup a maven project
    In fact, this is where I’ve spent a lot of times: get a predefined maven project, from which I could start my tests/devs.
    Here is my pom.xml

  4. 1st tip : a generic “Reporitory” class
    As I did in a previous post regarding Symfony and a kind of “super” controller, I quickly had the same approach with Persistence/EJB. I created a top repository class to quickly handle simple stuff with @Entity.
    Here is my (old) very first but efficient AARootRepo.java
  5. 2nd tip/reminder: Hibernate key events/annotations
    Type Description
    @PrePersist Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation.
    @PreRemove Executed before the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
    @PostPersist Executed after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed.
    @PostRemove Executed after the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
    @PreUpdate Executed before the database UPDATE operation.
    @PostUpdate Executed after the database UPDATE operation.
    @PostLoad Executed after an entity has been loaded into the current persistence context or an entity has been refreshed.

    These events are quite useful to handle “json” data embedded into a blob/text field (through PostLoad/PreUpdate/PrePersist) for example, or to automatically update a field on persist/update (PrePersist/PreUpdate).

 

Git – Remote Branch – Tips

A little memo when I need to start a git project from a remote branch and server:

git init
git remote add origin [server]
git fetch origin
git checkout -b [localbranchname] origin/[remotebranchname]

The 2 last lines are the most important. To view all branches:

git branch -v -a

For bitbucket (my favorite git repo), [server] will be something like

git@bitbucket.org:[login]/[project].git

 

Android: EditText Login/Password : intercept ‘OK’ and ‘ENTER’ on a LoginForm

Quick tips on a Login Form in an Android App, to enhance user experience: intercept ‘Enter’ in a TextView or ‘OK’ in a Numeric-only TextView

My Login Form is with a Relative Layout. Note that the Password field is numeric-only.

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/start_userid"
    android:hint="@string/start_userid"
    android:layout_alignParentTop="true"
    android:layout_marginTop="50dp"
    android:layout_centerHorizontal="true"
    />
<EditText
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:inputType="numberPassword"
 android:ems="10"
 android:id="@+id/start_passwd"
 android:hint="@string/start_password"
 android:layout_below="@+id/start_userid"
 android:layout_centerHorizontal="true"
 />

The code to intercept “Enter” Key in UserId field, and “OK” in numeric-only Password field is:

mUserId = (EditText) findViewById(R.id.start_userid);
mUserPassword = (EditText) findViewById(R.id.start_passwd);

mUserId.setOnEditorActionListener(
  new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_NULL && 
             keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
            mUserPassword.requestFocus();
        }
        return true;
    }
});

mUserPassword.setOnEditorActionListener(
  new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            doLogin(); // check login & so on
        }
        return true;
    }
});

Symfony 2 : Avoid doctrine’s memory leaks with commands

While running some specific long-time import processes through Doctrine by running a Symfony 2 command, I noticed some memory leaks.

I’m using MongoDB on top of doctrine.

For example:
First import : 22 MB used
Last import (100k+): 500+ MB used

Couple of tips:

  1. Call $dm->clear() regularly to clean up doctrine cache. But, do not forget that all objects in cache will be swept
  2. This is the REAL tip: add –no-debug to your command line
php app/console --no-debug my:bundle:command

The 1st tip helps a little bit, the 2nd one is very efficient. And it has another impact: it speeds up the execution.