ES6 Generator functions – A beauty !
ES6 Generator* function is one of the unique features which helps maintain a flat & clean code.
Example:
Let’s consider a simple example of getting pizza.
Promise based implementation:

Generator fn based implementation:

Explanation:
- Generator fn differentiates itself from other functions by *
ie., function* pizzaGenerator() or function *pizzaGenerator() - runGenerator() can be considered as a util that executes generator function.
- generator() returns iterator object which exposes next() that helps move to targets in sequence.
- yield in generator function*() is synonymous to pause. It helps pause the next line execution until the current execution result is obtained (be it function call or promise)
It’s usage has made my code very straight-forward, flat & clean.
References:
Webpack configuration for multiple environments : different ways
I had searched much on direct & easy ways of webpack configuration for multiple environments. I was not able to find a straight forward article and hence I’m writing about it.
To configure webpack manually for multiple environments (say dev/prod), we can do it in the following ways,
- Configure in a single file
- Configure in multiple files
Below is the difference between the both,
| Single File Configuration | Multi File Configuration | |
|---|---|---|
| When to use? | can be used when only few config properties between env differ. |
can be used when most of the config properties between env differ. |
| No of config files | single file for all env eg: webpack.config.js |
mutiple files used. One file for each env. eg: dev.js, prod.js |
| config definition | config declared as function & env is passed |
2.a) config declared as obj 2.b). config declared as fn -official link |
| package.json (script command) |
webpack –env= <env> | 2.a) webpack –config=<filepath/filename> 2.b) webpack –env= <env> |
| Disadvantage | code-cluttering increases with increase in different values for same config properties across env. |
repeatability of common env config properties across files. |
Therefore based on one’s project scope and need, one can choose which approach to go with.
Approach 1: Single File Configuration:
webpack.config.js:

Note: config is declared as a function with environment param.
package.json:
Add the below in the scripts section,

In the above command, --env tag passes environment as ‘development’ / ‘production’ to webpack’s config function.
Approach 2: Multi File Configuration:
Here separate files are created for each environment.
Note: Here config is declared as an object.
Approach 2.a) package.json:

In the above command, --config refers to the config-file-path .
Default file path is webpack.config.js or webpackfile.js
Other approaches:
- Approach 2.b) Invoke respective env files from webpack.config.js as given in official link (Manual way)
- webpack.config.js: Here config is declared as function. Respective env config files are invoked based on env.
- package.json:
webpack --env = <env>
- Automatic configuration for production:
webpack -p. Official link
ES6 modules & classes with Webpack: quick setup & usage
For setting up and using ES6 Modules with webpack perform the following steps:
- quicky setup js-sdk library using webpack
- Install babel-loader and its dependencies.
npm install babel-loader babel-core babel-preset-env --save-devHere babel-loader is the main package for invoking Babel transpilation. It requires babel-core for apis. babel-presets has the plugin for module-loading.
- Configure webpack.config.js
vi index.js
//Class definition export default class Imax { get movies() { return ['Logan', 'Beauty and the Beast']; } bookMovie(name) { return `Thank you for booking with Imax. Booking ID is ASDFFG|${name}`; } } module.exports = new Imax();- webpack // build library
- webpack-dev-server // host library. (hosted locally here)
- Client side:
$.getScript('//localhost:8080/assets/imax.js').then(() => { let selectedMovie = Imax.movie[0]; console.log('Movie list: ', Imax.bookMovie(selectedMovie)); }); - O/P:
Thank you for booking with Imax. Booking ID is ASDFFG|Logan
References:
Quickly setup JS SDK library using Webpack
Technology used:
- node version : 6.9.4
- npm version : 3.8.5
- webpack : 2.2.1
- webpack-dev-server : 2.4.1
Steps:
mkdir imax//project namecd imaxnpm initnpm install webpack --save-devnpm install webpack-dev-server --save-dev//for development use only
webpack-dev-serverhelps serve the webpack bundle.vi index.jsmodule.exports = { greetings: 'Welcome to IMAX movie booking', movies: ['Logan', 'Beauty and the Beast', 'Transformers'] }- Now on running
npm run build, the following error occurs,No configuration file found and no output filename configured via CLI option. A configuration file could be named 'webpack.config.js' in the current directory. Use --help to display the CLI options.webpack requires webpack.config.js file.
vi webpack.config.js
module.exports = { entry: './index.js', //app entry point output: { path: 'dist', //output directory absolute path publicPath: '/assets/', //public URL address of output files filename: 'imax.js', //output-bundle filename library: 'Imax' //helps export output-bundle as library } }
The configuration is done. Now execute the below commands,
npm run build
It internally invokeswebpack,which compiles & bundles the library file.npm start
It starts the dev server & serves the bundled file athttp://localhost:8080/assets/imax.js
Client side JS:
$.getScript('//localhost:8080/assets/imax.js').then(() => {
console.log(Imax.greetings);
console.log('Movie list: ', Imax.movies);
});
You can also directly add the script in html and use the library functions.
Output:
Welcome to IMAX movie booking Movie list: ['Logan', 'Beauty and the Beast', 'Transformers']
References:
Devil or Deep Blue Sea ? The pain in choosing the two heroic MVC frameworks
Of late, for the past few months I had been working on Ember. Few of my old posts would have been on angular-1.x. From my hands-on in both, I’m listing the pros and cons observed. This blog definitely doesn’t mean that I’m anti-angular now.
Angular and Ember both are client-side framework giants which help develop single page web applications. The below comparison is in reference to ember-1.x and angular-1.x
- Coding style:The significant difference that I felt when I was working with ember was its coding-standards – ’ember way of coding’
ie., In angular if there are different ways to do a single task and the developer can make the choice based on his needs, ember provides only one best way to do a task and the developer is forced to follow that. This inturn lead to clarity, reusability & scalability advantages when the app got bigger. -
Data Layer: Ember has an excellent optional data layer. Ember’s model classes help a great way in handling properties and its relationships, dirty checking etc.,In angular, we don’t have a proper model-base class. It attaches everything to $scope. Dirty check using $digest at times has performance lag.
-
Data Store: In Ember, we query data using ember data store query. The data fetched is then stored in ember-data-store. When second request is made, results are fetched from in-memory store.Whereas angular treats every request to be new. It discards what it already had and makes a request again. Though angular services help store data, they do not serve upto the capacity of ember-data-store.
-
Computed property in ember observes change in property value dynamically during runtime.In angular this is done using $scope.$watch but it gets tedious when that particular object had to exist in other controllers too also causing performance degradation.
-
Project Structure: Ember’s pod structure helps organise app in a feature driven approach i.e., our files are grouped by functionality rather than by type. This gives a lot of control and helps scale apps when they get bigger.Angular also helps structure code based on feature but angular is very flexible
The difference I would like to highlight here is Ember drives the pod structure, whereas in angular the developer drives the structure.
Accepted that, there was a havoc in developers mind when we where told that almost most of the code in angular-1.x cannot be reused / migrated to angular-2.x. This created a little tension and confusion while selecting frameworks.
However now looking at angular-2.x features (like performance optimisation, native support, es6 & es7 features), it’s sharply showing that it would give a great reach for forthcoming projects which would implement it.
Ember-2.x is also of no less with its features like very high speed performance, server-side rendering etc., [Ember-2.x coupled with Glimmer engine – the app is going to fly].
Having worked in both the frameworks, I feel Ember and Angular both are close to eachother and are equally good. The main determinant in choosing the framework is the learning curve, community support, regression free migration to releases, time to deliver etc.,
Error: [$interpolate:interr] http://errors.angularjs.org/1.3.15/$interpolate/interr? and $sce
Problem:
When trying to load an iframe with url value fetched from controller, interpolate error occured as follows,
Error: [$interpolate:interr] http://errors.angularjs.org/1.3.15/$interpolate/interr?p0=%7B%7BembedUrl%7D…%2Finsecurl%3Fp0%3Dhttps%253A%252F%252Faishwaryavaishno.wordpress.com%252F
at Error (native)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js:6:417
at v (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js:88:110)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js:109:321
at Object. (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js:107:493)
at n.$digest (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js:123:221)
at n.$apply (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js:126:293)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js:17:479
at Object.e [as invoke] (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js:36:315)
at d (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js:17:400)
Reasoning:
Interpolate means , to alter/corrupt by adding something new. Angular assumed url loaded in iframe to be a corrupt one.
Solution:
This problem can be solved by using $sce service(Strict Contextual Escaping) with which we can mark the object(url) as safe.
app.controller("DemoController", function ($scope,$sce) {
url='https://aishwaryavaishno.wordpress.com/'
$scope.embedUrl=$sce.trustAsResourceUrl(url)
})
In the above code, url that has to be fetched in iframe is passed through $sce.trustAsResourceUrl(url). It returns an object that is trusted by angular which can further be used in ng-src.
Did you know that, the above problem can also be solved by whitelisting url.
Quick Notes on Angular: Difference between angular.module(“app”) and angular.module(“app”,[])
- angular.module(“app”,[]) – helps define a new module called “app” . The array will contain different other modules that this app-module depends on.
- angular.module(“app”) – helps to get the reference of the already created “app” module.
Reference:
Autocomplete not working in Netbeans – 8.0.2
- Delete everything in the cache directory of netbeans
rm -rf ~/.cache/netbeans/8.0.2/* - Restart Netbeans
Reference:
https://netbeans.org/bugzilla/show_bug.cgi?id=247026
https://forums.netbeans.org/topic61787.html
Unsatisfied Dependency Exception : CDI 1.1 + Bean Validation + GlassFish 4.0 -> requires jersey-gf-cdi.jar upgrade
Recently, I faced Unsatisfied Dependency Exception, when trying to integrate BeanValidation with CDI 1.1 . Independently (without integration) everything worked fine. Looks like, the present Glassfish version 4.0 doesn’t support CDI 1.1 + Bean Validation together.
To be still clearer, Jersey (reference implementation for JAX-RS) jar related to CDI i.e., jersey-gf-cdi.jar in GF-4.0 version, is not supporting this integration .
I made the below changes, for Bean Validation integration with CDI 1.1 in Glassfish 4.0 to work.
Applicaiton Server used : Glassfish 4.0
Technology : JEE-7, CDI 1.1
Exception Trace :
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=Foo,parent=Foo,qualifiers={@foo()}),position=-1,optional=false,self=false,unqualified=null,350112977)
at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
at org.jvnet.hk2.internal.Utilities.justInject(Utilities.java:771)
at org.jvnet.hk2.internal.ServiceLocatorImpl.inject(ServiceLocatorImpl.java:790)
at org.glassfish.jersey.gf.cdi.CdiComponentProvider$1.inject(CdiComponentProvider.java:316)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:158)
at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:69)
………………………….
Solution :
- Download jersey-gf-cdi-2.0.jar . Download specifically 2.0 version for glassfish4.0. If other higher versions 2.10 are used, incompatibilty with other jars (firstly with jersey-server.jar) will arise.
- Rename the jar to jersey-gf-cdi.jar
- Replace it in glassfish4.0/glassfish/modules/
- Delete osgi-cache folder -> Path : glassfish4.0/glassfish/domains/domain1/osgi-cache
- Refresh and restart glassfish. New osgi-cache will be created in domain 1 with the latest jersey-gf-cdi.jar. Problem will be solved 🙂
This issue will be resolved in Glassfish-4.0.1 version (not released yet). We’ll have to do the above till GF-4.0.1 is released.
Have a great day 🙂
Reference :
https://java.net/jira/browse/GLASSFISH-20597
CDI – Lifecycle Management by Container
We know that, CDI Managed Beans are contextual. Their lifecycle management is done by the container. One of its main advantages is type-safe dependency injection.
But how does it do it?
In the below code, during application initialization process, the container checks for Type-Safe Resolution for News bean annotated with @Inject and then instantiates it.
TYPE-SAFE RESOLUTION:
Here the container checks ,
- if the bean type is equal to the required type(type: News here) at the injection point in Consumer Bean class.
- if the qualifier of bean is equal to the required qualifier at the injection point.
(If no qualifier specified , then default qualifier is @Default)
@Stateless
public class News {
public String getLatestNews(){
return "FIFA 2014 WorldCup";
}
}
@Stateless
@Path(value = "consumer")
public class Consumer {
@Inject
private News news;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("latestNews")
public String tweetLatestNews(){
return news.getLatestNews();
}
}
Any mismatch will result in unsatisfied or ambiguous dependency problem.
CREATION AND DESTRUCTION BY CONTAINER:
- Internally, the contextual instance of bean is created by the container, by calling context.get() (of javax.enterprise.context.spi.Context interface) which inturn calls Contextual.create() implementation (of javax.enterprise.context.spi.Contextual Interface) to get contextual instance of bean.
- During destruction , the above contextual instance created is passed to Contextual.destroy() by context object for destruction.
Reference:
http://www.oracle.com/technetwork/articles/java/cdi-javaee-bien-225152.html
http://docs.jboss.org/weld/reference/latest/en-US/html/injection.html
http://docs.jboss.org/cdi/spec/1.0/html/contexts.html
http://docs.jboss.org/cdi/spec/1.0/html/injectionelresolution.html#ambigdependencies