5 Minute JavaScript #19: Polyfills

The past few weeks were dedicated to the useful array methods. However these methods have been implemented in ECMAScript 5 and are therefore not available in older browsers such as IE8 and sometimes we have to support legacy browsers.

In JavaScript, we use polyfills to create behavior that is not implemented in browser. We can use polyfills to add every kind of behaviour to our application and a lot of websites provide these polyfills.

Basically what happens is that we first do a feature detection. Is the feature available in the browser? For example, does Array.prototype.map exist? Yes? That’s great! It means the feature has been implemented and is probably faster than every polyfill that we could come up with. Is it not available? Too bad, but we can create the Array.prototype.map method ourselves.

The Mozilla Developer Network has some of the most robust polyfills that are still fast in use. It also has an excellent documentation about the array methods. Here’s the page for the map functionality.

Using a polyfill doesn’t change the way the method is being called. If your browser does not support the map-method and you use a polyfill, you will still use it like this: [1, 2, 3].map(…); This is useful, because you don’t have to change syntax for different browsers.

Another solution is to use a framework that has implemented these functionalities. One of my favourites is underscore. This framework adds more useful methods than just the array methods to your function toolbelt.

framework adds more useful methods than just the array methods to your function toolbelt.

JEE : Using EJB and Context annotations in a JAX-RS Provider class

A lot of new annotations have been introduced since the JEE6 spec. Before we had EJBs and servlets to cover most of our server-side objects in a JEE application. But in JEE6, CDI and JAX-RS have been added, along with a few other JSRs that are implemented using annotations. This results in a long list of annotations, where – in my opinion – it is not always clear which one to use, nor to understand how they work together.

In this blog, I would like to show you how EJB and CDI work or don’t work together, in combination with a JAX-RS Resource.

JAX-RS is used for writing REST-services. It allows you to create these services, simply by annotating a Java class.

This is our REST service class aka “resource class”. It will create a REST service on the /test url, an it returns a String. Here, for test purposes, we always generate a RuntimeException.


@Path("/test")
public class TestResource {
@GET
public String getCustomer() {
if (1==1) throw new RuntimeException("Whoops, something goes wrong");

return "Customer ABC";
}
}

Because we don’t want to send a stack trace to the client, but a meaningful response in the form of an Error class, we use a provider class and annotate it with @Provider (javax.ws.rs.ext.Provider). This annotation is part of the JAX-RS spec.

Annotating a class with @Provider – according to the API-documentation – “marks an implementation of an extension interface that should be discoverable by JAX-RS runtime during a provider scanning phase.”

Our provider class will catch any exception thrown by the resource class, and send a proper response object to the client instead.

The returned Error class, that will be marshalled to an xml object and returned to the client :

@XmlRootElement

public class Error {
private String desc;
public Error() {
super();
}

public Error(String desc) {
super();
this.desc = desc;
}

public String getDesc() {
return desc;
}

public void setDesc(String desc) {
this.desc = desc;
}

}

The provider class that will catch any exception and return the error class looks like :


@Provider

public class GenericExceptionMapper implements ExceptionMapper<Exception> {

@Context HttpServletRequest httpRequest;

public Response toResponse(Exception ex) {
return Response.status(500).entity(new Error("Error during call with method : "+httpRequest.getMethod())).build();

}

}

As you can, see, we use the @Context annotation to access the current http request. When an exception is thrown by the resource class, it will automatically be handled by the toResponse method of our provider class. It returns a response, containing the Error class, that will be sent to the client in xml format. This is done by the JAX-RS framework.

Now we have an EJB bean that we want to use in order to log this error to a database, before sending the response. So we will add this to the provider class as follows :


@Stateless

@Provider

public class GenericExceptionMapper implements ExceptionMapper<Exception> {

@Context HttpServletRequest httpRequest;

@EJB ErrorEJB errorEJB;

public Response toResponse(Exception ex) {
// log the error to the database
errorEJB.logError(ex));
// return the response
return Response.status(500)
.entity(new Error("Error during call with method : "+httpRequest.getMethod()))
.build();
}

We made the GenericExceptionMapper a stateless bean using @Stateless, in order to be able to inject the ErrorEJB into the provider.

But now, we will get a NullPointerException on the httpRequest.getMethod, as the @Context annotation won’t work  anymore.

This is because, before our update, we only used the @Provider annotation , so this class was a CDI bean. With CDI, the container looks up the injected classes in a “scope”, which will basically be a hashmap that exists for a specific period of time :

  • @RequestScoped : per request
  • @SessionScoped : per HTTP session
  • @ApplicationScoped : per application

Into that environment we can inject the HttpServletRequest using the @Context annotation

By adding the @Statefull annotation, we made an EJB from our CDI bean.

With EJBs, the container looks also into a hashmap, but checks if the bean is of type @Stateful, @Stateless or @Singleton. So it isn’t aware of any http context.

In order to solve this problem, we will inject the our ErrorEJB as CDI bean iso an EJB.

This can be done as follows :

  • replace the @Stateless by @RequestScoped
  • replace @EJB by @Inject
  • adding an empty beans.xml file to the WEB-INF

Which gives us :


@RequestScoped

@Provider

public class GenericExceptionMapper implements ExceptionMapper<Exception> {

@Context HttpServletRequest httpRequest;

@Inject ErrorEJB errorEJB;

public Response toResponse(Exception ex) {

errorEJB.logError(ex));

return Response.status(500)
.entity(new Error("Error during call with method : "+httpRequest.getMethod()))
.build();

}

Now for JEE7, there are even more annotations available, so make sure to check the docs before using them.

5 Minute JavaScript #18: reduce

The past weeks we dived in the wonderful world of array methods. Previously we already discussed forEach, filter, some and every, and map. Today we’ll take a look at the reduce method. While being extremely useful, its concept can be hard to grasp.

Also known as fold (in this case foldLeft) in other functional programming languages, reduce kan be used to combine all elements of an array into one single return value. That return value can be anything. It could be an array (then the reduce functions as a filter/map), but it can also be: an object, string, number, boolean… Everything is possible.

A simple example can be to use the reduce method for calculating a sum. Here’s the code how we would write it in any other imperative language.

var numbers = [1, 2, 3];
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
	sum += numbers[i];
}

We can rewrite this code as follows using the reduce method

var sum = numbers.reduce(function (prev, cur) { return prev + cur; });

The reduce callback function takes two important parameters (prev, cur in this case). First of all we have the previous value. This is the value that got returned in the previous callback function. The current parameter is the current item in the list.

You might get your head around this functionality, but it’s not really useful in real applications. Its real strength lies in the fact that you can press a lot of elements together into one single return value. A use case for reduce might be this:

var user = { id: 'UUID', version: 0 };
var users = [/* list of users */];
var idVersionMap = users.reduce(function (map, user){ 
    map[user.id] = user.version; 
    return map; 
}, {});

In our blogpost about the map method we used map to create a new list of objects (with id and version). Here, we use the reduce method to create a single object that acts as a map with key = id and value = version. The empty {} that we passed along in the reduce callback function is the initial value the method needs to use.

Introduction to Oracle Database 12c

With the launch of DB 12c in 2013, Oracle introduced a new architectural concept, called “multitenant databases”, where you have one super database (=container; CDB) and one or more sub databases (= pluggable DBs; PDB).

Before running the installer on an Oracle Linux 6 environment, a library can be installed through yum to meet all the system per-requisites:

yum install oracle-rdbms-server-12cR1-preinstall

The software installer and DBCA are similar to 11g, except for this screen where you can pre-configure your CDB and PDBs:

db12c01

This DBCA execution will not only create a CDB and 1 PDB, but a “seed pluggable database” as well.  You can use this seed database as a template to create other pluggable databases.

db12c02

By default, after running the DBCA, all CDBs and PDBs are up and running.

Now, we will reboot the host machine and try to start all of our components.

Is there a difference when starting the listener and the CDB?

No!  You can start the listener and your CDB in exactly the same way as you did with your pre-12c database.

How can you connect to the CDB?

Very simple: just the same as in the past with pre-12c databases.

$ sqlplus system@apexdev

SQL*Plus: Release 12.1.0.1.0 Production on Thu Mar 19 22:53:55 2015

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

Enter password:

Last Successful login time: Mon Mar 16 2015 22:20:50 +01:00

Connected to:

Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 – 64bit Production

With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

SQL>

Are the PDBs opened by default, when starting the CDB?

No.  This can be verified by this query:

SQL> select open_mode from v$pdbs where name=’APEXDEV_PDB1′;

OPEN_MODE
———-
MOUNTED

The PDB is mounted; to open it, just run this command:

SQL> alter pluggable database apexdev_pdb1 open read write;

Pluggable database altered.

SQL> select open_mode from v$pdbs where name=’APEXDEV_PDB1′;

OPEN_MODE
———-
READ WRITE

Note: this must be done as “SYSDBA”.

How can we connect to the PDB?

There are 2 methods:

First method: connect to the CDB and then switch to the PDB by setting the container:

$ sqlplus system@apexdev

SQL> show con_name

CON_NAME
——————————
CDB$ROOT
SQL> alter session set container=apexdev_pdb1;

Session altered.

SQL> show con_name

CON_NAME
——————————
APEXDEV_PDB1

Second method: Modify your tnsnames.ora file by adding an entry for the PDB, based on the CDB entry.

Now, you can connect as usual to the PDB:

[oracle@ol6db1 oracle]$ sqlplus system@apexdev_pdb1

SQL*Plus: Release 12.1.0.1.0 Production on Tue Mar 24 20:37:38 2015

Copyright (c) 1982, 2013, Oracle. All rights reserved.

Enter password:
Last Successful login time: Thu Mar 19 2015 18:59:51 +01:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 – 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

SQL> show con_name

CON_NAME
——————————
APEXDEV_PDB1

As you can see, it is all quite easy.  One of the main benefits of this architecture is that you can handle every PDB as a separate database that can be upgraded or plugged/unplugged independently from other databases.

And of course your database will be ready for the cloud!

5 Minute JavaScript #17: some and every

In the previous blogpost we discussed the map method on arrays in JavaScript. We still have some useful methods the go. Next in line are the some and every methods. These methods are similar and can be very useful when validating data.

var isEven = function (n) { return n % 2 === 0 };
var areAllEven = [2, 4, 6].every(isEven);
var someEven = [1, 2, 3].some(isEven);

The every method will check if for every element in the list, the callback functions returns true. If there is one single item in the array that returns false, the every method will return false as well. The some method is satisfied when there is at least one element in the array where the callback returns true.

var stockItem = { hasBeenShipped: true };
var selection = [/* list of stock items selected in a list */];
var hasNotBeenShipped = function (si) { return !si.hasBeenShipped };
var hasBeenShipped = function (si) { return si.hasBeenShipped };

$('#sendStockItems').attr('disabled', selection.every(hasNotBeenShipped));
$('#sendStockItems').attr('disabled', selection.some(hasBeenShipped));

The example here will disable a button when the selection in the list contains one or more items that already have been shipped. This code is very readable and concise. You can almost read exactly what it does: set attribute disabled when selection has some items that hasBeenShipped.

5 Minute JavaScript #16: map

Last week we took a look at the filter functionality. This week I will show you one of my favourite array methods called: “map”. It’s extremely powerful and useful in so many ways. The purpose of map is simple, it transforms an item in an array and pushes that transformation into a new array. The method then returns that newly created array with all the transformed items. A simple example will show you what it does.

var square = function (item) { return item * item; };
var squares = [1, 2, 3, 4].map(square);

In this example we just square a number in the array. The result will be a new array but with the squared items.

This example is easy to understand, but you might wonder what the practical use is for this function. Well in a lot of applications I find myself using map to select the identifier from an object and pass along a map of id’s.

var user = { id: 'UUID', version: 0, name: 'User 1' };
var users = [/* a list of users */];
var ids = users.map(function (u) {return u.id;}); 
var versions = users.map(function (u) {return u.version});
var idsAndVersions = users.map(function (u) { 
    return { 
        id: u.id, 
        version: u.version 
    };
});

These lists can be used in frameworks, api’s, ajax requests, caching, etc… everywhere you don’t need to know / send the full information of the user.

5 Things I wish I knew about APEX when I just started (part 3)

In my previous post of this series, I talked about cookie sharing in APEX. The next post in this series is about build options, I hope you enjoy it.

Build Options

Imagine having to release an apex application, but you don’t want some parts released in to the production environment yet, because they are unfinished, or not tested. Or you want to disable a module in your application for some reason.

Apex provides a solution for this called build options.

You can find the build options under shared components > logic > build options

Let’s create 2 build options:

The first one will keep the component active in our development environment, but will disable it on export so the developed content is disabled in our production environment.

buildoptions1

The second one will disable content in the application, and take over this behavior on export to our production environment.

buildoptions2

For the status there are two options possible:

Exclude, will disable the content in the current application, and include will keep it enabled in the current application.

For the default on export there are 3 possible combinations:

Same as current will take over whatever has been chosen in status when exporting a page. Exclude will disable the components on export of the application. Include will enable the components on export of the application.

Build options can be attached to any component in apex: pages, processes, regions, items, and can be found under the configuration tab when editing the components.

buildoptions3

As a test you can put the 2 build options on some page items in your current application.

When you run the page you will notice that in your development environment, one item will be visible and one will be gone from the page.

When you take an export and import it back in the new environment you will notice both items are removed from the page.

That’s it! The fourth blog in this series will be about recovering applications and page elements using flashback, and will be online soon.