Sunday, August 23, 2020

Understanding JavaScript Prototypal Inheritance for Java developers

Inheritance is a fundamental concept in programming languages. However, it is implemented differently in Object-Oriented Languages such as Java and Javascript. 

I have seen developers who move from OOP languages such as Java struggling to understand the JS Inheritance consequently end up not using it altogether which can also lead to inefficient code.  

In this post, I will try to explain the JS Inheritance also called Prototypal Inheritence especially for those who come from OOP languages.

Background

Let's quickly define Inheritance first. In simplest terms, it is a mechanism by which one object can acquire properties and behaviors or other objects. This is one of the main tenets of most common Object-Oriented Programming (OOP) languages and promotes reuse. This represents an IS-A or parent-child relationship. OOP languages implement what is called Class Inheritance.

Javascript also allows Inheritance but it is implemented entirely differently from OOP languages and is called Prototypical Inheritance. For OOPs languages such as Java has the concept of Classes and Instances and they are separate. Instances (objects or entities) are created from Classes (generalization or blueprints/definition) but in Javascript, there is no concept of class - you don't define a class and then create instances from them. 

Note that similar to Java language Javascript does not support multiple inheritances - the object has only one prototype and therefore can only inherit one object. Note that Java does support inheritance of more than than one interface.

Prototypal Inheritance

Before we talk about Inheritance in Javascript we need to understand what is a Prototype. 

All objects in JS can have properties that you define. For example, here object obj1 has two properties, foo, and bar

function Function1() {
this.foo = 'value1',
this.bar = 'value2'
}

In addition, all functions have one additional hidden property called prototype which by default is an empty object. Using this hidden property you can extend ALL objects created using function constructor (using the new keyword) and define new methods or properties. 

var obj1 = new Function1();
Function1.prototype.baz = 'value3';

Function1.prototype.getProps = function() {
return this.foo + ', ' + this.bar + ', ' + this.baz;
}

console.log(obj1.baz)
console.log(obj1.getProps())

Output

value3
value1, value2, value3

In the above example, we used the hidden prototype property of the object and enhanced or extended it by adding one property and a new method. Internally the prototype is implemented as __proto__ property and even though you can access it directly it should not be used directly. 

console.log(obj1.__proto__)

Function1 { baz: 'value3', getProps: [Function] }

The prototype object can also further have a __proto__ object. This is called the prototype chain. You can have another object that points to the same prototype as defined for the first object. During execution, the javascript engine starts at the top of the chain and works its way down till it finds the property in the prototype chain. The bottom of the prototype chain is Object{}. This mechanism of looking though the prototype chain is also called Delegate Prototype.

The example above uses Method Constructors and is considered an old way. 

Note that EC6 introduced the class keyword to Javascript language which you can use to create an object. Note that even though it looks like Classes in OOP languages such as Java, it is not the same. class in Javascript is a type of function and uses class instead of function keyword and also has a constructor method to initialize class properties based on the passed parameters. The only difference between Function constructor and using class forces you to use new keyword otherwise you will get an error.  

The new and preferred way (supported by newer browsers) is to use Object.create passing a prototype object and using dynamic linking to setup properties on the object. This is also referred to as Pure Prototypal Inheritance. You don't need to use class, extends, constructor, or super. 

var User = {
firstname: '',
lastname: '',
getName: function() {return this.firstname + ' ' + this.lastname},
}

var Member = Object.create(User);
Member.registrationDate = new Date();

var John = Object.create(Member);
John.firstname = 'John';
John.lastname = 'Doe'
John.registrationDate = new Date(2020, 7, 23, 10, 33, 30, 0);
console.log(John)
console.log(John.__proto__)
console.log(John.__proto__.__proto__)

console.log(John.getName())

console.log(John.__proto__.__proto__.__proto__)



Output
{
firstname: 'John',
lastname: 'Doe',
registrationDate: 2020-08-23T17:33:30.000Z
}
{ registrationDate: 2020-08-24T02:15:02.161Z }
{ firstname: '', lastname: '', getName: [Function: getName] }
John Doe
{}

Let's walk through the code and try to understand what's going on here.

First, We created a User object (initialized to default empty values for first and last names) using object literal syntax. Then extended the User object using Object.create and added a new property registrationDate set to the current date by default. Then created one user object John and passed Member object and overridden the default values. 

The first console log for John shows all the properties of John. 

The next two console logs show prototype chains. The first one pointing to Member object and the prototype of that points to User.

To resolve John.getName() JS execution context traverses the chain all the way to base object (User) and find the getName method and displays the first and last name. 

Finally, the console log statement logs the prototype of the base object which is an empty object {}.

The key thing to understand here is that even though you did not explicitly set the getName method on John object using prototypal inheritance it was able to access it. Note that if you now add a new method to any of the prototypal chain all the objects will inherit this new method. 


Finally, you can use prototypal inheritance to extend or override the behavior of built-in function constructors. For example, refer to this article.

Besides code reuse are there any other benefits of Prototypal Inheritance

Yes. The properties and methods in function constructor occupy memory. If you are instantiating a very large number of objects the attributes will be duplicated across all objects. While you do need attributes defined in the base object store the state variables there is no need to have functions methods that operate on object attributes to be duplicated across all objects. 

Using prototypal inheritance you can extend the behavior of all objects by defining them using prototypal inheritance thereby reducing the memory pressures. 

Sunday, August 16, 2020

Using GCP Source Repository, Cloud Build to configure automatic deployment of docker container on Google Cloud Run

Introduction 

In this article I will walk through the steps required to setup continuous integration environment and create build pipeline and automate deployment of a sample Angular App on Google Cloud Run. I will be using GCP stack end-end. Cloud Source Repositories for Git repository for version control, Cloud Build for creating docker containers which will be stored on Container Registry and then deploying the image on Cloud Run - serverless runtime environment. Finally, I will outline steps for configuring automated integration/deployment that will trigger builds and deployment of new version of application for any merge. 

Key Concepts and Services

Cloud Source Repositories - Fully managed free git repository from Google Cloud to storing and version control of source code. Tightly integrated with Cloud Build for triggering build for continuous integration. 

Docker - software that is most popularly used to build containers. Docker would combining the application code and set of instructions called DockerFile and produce a container that contains code all the required dependencies (listed as part of instructions in the docker file) to run the code. 

Containers - a self contained environment that can be run on many platforms 

Cloud Build - provide service similar to Docker and integrated with Cloud Source Repositories and can be triggered to produce container images and provides Continuous development and Continuous deployment. Cloud build can be configured to push the images to container registry and deployed to Cloud Run

Container Registry - Google Cloud Repository that can be used for hosting container images produced by Cloud Build

Cloud Run is fully managed serverless compute platform to deploy and running containerized application. Managed Serverless environment allows you to focus on your application and not worry about the underlying infrastructure or setting up and managing runtime environments. 

Saturday, August 08, 2020

Installing VNC Server on Google Cloud CentOS VM

Introduction

Recently I installed VNC on CentOS 6 on GCP for some development work. Sharing my notes. The steps are similar for Redhat Enterprise Linux.

Concepts

VNC - Virtual Private Networking, a Graphical User Interface platform that can be accessed remotely 

Steps

Create a VM

Create a CentOS instance in Micro VM Shape. To reduce latency choose a region close to you. Note that I'm using default VPC network that is automatically created. If you need more details on how to create VM pls refer my earlier blog

gcloud beta compute --project=oci-gcp-vpn-connectivity instances create centos-vnc-demo --zone=us-central1-a --machine-type=f1-micro --subnet=default --network-tier=PREMIUM --maintenance-policy=MIGRATE --service-account=71492557944-compute@developer.gserviceaccount.com --scopes=https://www.googleapis.com/auth/devstorage.read_only,https://www.googleapis.com/auth/logging.write,https://www.googleapis.com/auth/monitoring.write,https://www.googleapis.com/auth/servicecontrol,https://www.googleapis.com/auth/service.management.readonly,https://www.googleapis.com/auth/trace.append --image=centos-6-v20200714 --image-project=centos-cloud --boot-disk-size=20GB --boot-disk-type=pd-standard --boot-disk-device-name=centos-vnc-demo --reservation-affinity=any

Tuesday, August 04, 2020

Hybrid Cloud - Setting up Site-to-Site IPSec VPN Connectivity between Oracle and Google Cloud

Introduction


As enterprises move to cloud there is a need to connect cloud-native applications with on-premise legacy systems. Multi-Cloud architectures allow you to build solutions spanning more than one public cloud by combining best of breed capabilities creating an increasing need for interconnecting these clouds. For example, you may want to use the Google App Engine to deploy your app but for your backend prefer Oracle ATP database hosted on Oracle Cloud. 

Each public cloud provides multiple connectivity options from dedicated high speed interconnect to using VPN based technologies to connect to on-premise using IPSec based connections that use public internet but provide secure connectivity.

Oracle OCI offers service called VPN Connect for site-to-site connectivity between an on-premise network with OCI VCN using VPN based on the IPSec protocol. 


In this blog, I will outline steps for configuring VPN between Oracle OCI Private Subnet with Google GCP VPC. VPN using IPSec is a cost-effective way of connecting these networks over public internet obviating no need for expensive lease lines and such. Steps outlined here also apply if you are trying to connect your on-premise network with either of these two cloud service providers. 

Note that I will focus on Site-to-Site connectivity based on IPSec protocol and use out-of-the-box functionality for VPN provided by these two cloud providers. You can also use other VPN implementations such as open-source Strongswan and Libreswan. 

Thursday, July 30, 2020

Creating a Utility VM on Google Cloud (GCP)

Introduction


This blog is in continuation of my previous article - Oracle OCI Cloud - Connecting a Private VM from a Public Bastion Host and walk through steps for creating a VM instance on Google Cloud GCP which we will use to establish VPN connectivity with Oracle Cloud - the steps for which will be outlined in next article in this series. 


Here's a quick reference of configurations for this VM that we will be using in the next article while configuring VPN connectivity


VPC: gcp-oci-vpn-demo

VCN CIDR: 192.168.0.0/16


Subnet: subnet1

Region:  europe-west1

Subnet CIDR: 192.168.0.0/16


VM: instance-1

Public IP: 35.210.10.232

Private IP: 192.168.0.2

Thursday, June 04, 2020

Oracle OCI Cloud - Connecting a Private VM from a Public Bastion Host

Introduction


The following outlines the configuration for connecting a backend private instance though a public instance in the same VCN but different subnets. 

This post talks about the necessary configurations of Router, Firewall, and builds a complete end-end example. 

High-Level Steps

  • Create VCN and two subnets (one public, one private)
  • Create VMs - one in each subnet
  • Configure Router
  • Configure Firewall
  • Test and Verify
  • Access to OCI Instance

Note this is part one of the multi-part series wherein we extend this example and do necessary configuration on OCI and try to establish Hybrid Connectivity to a private instance on Google Cloud (GCP) using VPN.

Pre-requisites

  • User with necessary privileges to create VCN, VM and configure networking
  • SSH key (public and private key pair) - Basic knowledge of networking - CIDR, Routers, Firewall, etc..

Monday, November 18, 2019

OIC: Monitoring REST APIs examples using curl

Continuing the series of my previous posts on examples of OIC rest apis in this blog I will provide some additional examples of using curl to retrieve monitoring data.  

Getting logs

curl -X GET -H 'Authorization: Bearer access_token' -o <ics_log>.zip https://instance-name.us.oraclecloud.com/ic/api/integration/v1/monitoring/logs/{id}

 curl -u username@email.com:password -X GET  -H "Content-Type:application/json" -o flow_logs.zip https://instance-name.integration.ocp.oraclecloud.com/ic/api/integration/v1/monitoring/logs/icsflowlog

Valid values for log id: icsflowlog, icsdiagnosticlog, icsauditlog

You can provide additional parameter for filtering the result - for example following will return data for last one day. 

 curl -u username@email.com:password  -X GET  -H "Content-Type:application/json" -o flow_logs.log https://instance-name.integration.ocp.oraclecloud.com/ic/api/integration/v1/monitoring/logs/icsflowlog "q={timewindow: '1d'}"

For the next set of apis you can filter the result by time period, time window and also by the integration by adding following additional parameters

You can use time window as well - must be entered in - 'yyyy-MM-dd HH:mm:ss' UTC format

"q={startdate : '2016-09-23 07:07:07', enddate : '2016-09-23 08:17:07’}"

And filter the results for a given flow…

"q={timewindow: '3d', code: HELLO_WORLD, version: '01.02.0000'}” 


Friday, October 18, 2019

OIC: REST APIs Examples for managing Integrations

Expanding upon the last article I'm providing additional details and examples for using Oracle Integration Cloud REST APIs for managing your integrations. 

Note that for the examples below I will be using one of the pre-packaged integration named Hello World (version 1.2.000)

To limit the size of this posting I'm just providing examples only and limiting to common use-cases (small subset of the options). For additional details and completeness pls refer the official doc - REST API documentation. 


To get list of Integrations

curl -u username@email.password  -v -H "Content-Type:application/json" -H "Accept:application/json" -X GET https://instance-name.integration.ocp.oraclecloud.com/ic/api/integration/v1/integrations


Export one integration 

 curl -u username@email.password -X GET  -H "Content-Type:application/json" -o ./HELLO_WORLD_01.02.0000.iar_BAK https://instance-name.integration.ocp.oraclecloud.com/ic/api/integration/v1/integrations/HELLO_WORLD%7C01.02.0000/archive 


Friday, October 11, 2019

OIC: List of Integrations by Creator

Oracle Integration Cloud provides rich set of REST APIs to manage your connections/integration and life-cycle events. See details here for complete set.

There the APIs to get list of integration in JSON format but at this point there is no out of box API support for filtering out the results by creator or author of the artifact. One can use common programming language to parse the filter out the results but that require additional effort.

In this blog, I will provide simple command line means of achieving that. We will use curl and one command line library to parse JSON data - https://stedolan.github.io/jq/ 

The following was developed and tested on Mac OS (Mojave 10.14.6 ) and OIC version 19.3.1.0.0 (190624.1100.29533)

Install jq
brew install jq

Get list of integrations

Replace the highlighted (in blue) for your environment...

curl -u username@email.com:password -H "Content-Type:application/json" -H "Accept:application/json" -X GET https://instance-name.integration.ocp.oraclecloud.com/ic/api/integration/v1/integrations | jq '. |  {code: [.items[].code]}'


Friday, October 30, 2015

3 days in Amsterdam & around

After my short visit to London, I flew to Amsterdam and spent 3 days exploring the place. It was an awesome experience - quite a contrast from London on many levels. Sharing some highlights.

Amsterdam is unique in many ways - historical buildings, more canals than Venice, more density of Museums than anywhere else in the world, more bikes than population, friendly and relaxed environment, and perhaps most liberal city you will visit with legalized recreational drugs, same-sex marriage, and euthanasia! 

For my stay, I picked a hotel near Schipol Airport. Amsterdam city is about 15 - 20 mins train ride from the airport. You can buy 3-day Amsterdam Travel Ticket (25 euros) that allows you unlimited train, tram, and bus rides. 


Thursday, October 29, 2015

3 days in London

London is a travelers paradise - it has everything - famous buildings and landmarks, world-class museums, outstanding restaurants, fabulous retail, and plenty of green space and all of history to go along with that. 

Earlier this month I was traveling back from India to Los Angeles and took a break journey to spend 3 days in this beautiful metropolis (also spent some time in Holland - but that's for another post). Having born and brought up in India with centuries of colonial rule, Britain has a profound influence on India's history and culture. So, it was an even greater interest that I was looking forward to my visit to London.

I had some luggage so picked a hotel near Heathrow airport in Hounslow City - in the hindsight not a good idea to stay far from central London since wasted so much time every day traveling to the city.

London is very well connected by train/bus and oyster travel-card that allows to travel on any train/tube or bus is perhaps the best way to move around - great value and saves you a lot of time - I bought a 3-day pass for around 20 pounds. I also bought London Pass (approx 80 pounds) separately that cover entry ticket for most attractions (note you can purchase Oyster Travelcard with London Pass also)


Wednesday, May 01, 2013

My best golf round so far - 2 over

Yesterday was lucky day for me - shot my best round for 18-hole regulation course - 72 (2 over total with 4 over in front and -2 in the back) at Azusa Greens. Had one eagle and 2 birdies. Putting was not too bad either - 29 total puts with 6 one puts 6 - 15 ft range. Score would have been little better if not for bummer on par 3 13th - missed 2 footer and bogeyed from 15 ft with 3 puts!!.
This eclipses my previous best of 73 at Alhambra Golf Course which is bit easier course to play - rating/slope/rating of 64.8/114. Measuring around 6200 yrds Azusa Greens is not really long with rating/slope of 69/118 but some fairways are narrow with trees on the side.

Sunday, February 10, 2013

Pilot for a day


Today me and my friend went out on our first experience flying a plane. It was cold day (around 45 deg f) and partly clouds. After small briefing about key aircraft instruments and practicing for about half an hour on simulator, we were ready for our maiden flight. With trainer on the side and my friend on the back seat, I took control of small 4- Seater around 40 year old Piper PA -28 (http://en.wikipedia.org/wiki/Piper_PA-28). Starting from Van Nuys airport for a short 40 mins flight, we passed around LA downtown, Hollywood sign, Griffith park, and Pasadena to finally land at El Monte airport.

Personally, the take off was most scary of all. With takeoff speed around 60 knots - approx 70 mph which is not all that fast, and no horizon in sight for few mins (seemed much longer) and the plane gaining fast elevation, matched only by rising heart rate, the sheer exhilaration of takeoff was very soon replaced by the doubt and fear of placing trust on small and not so powerful and old piece of machinery. It made me wonder if this little escapade was well worth the risk and this adventure was nothing but a big mistake. Fortunately, once we leveled off around 2000 ft, the flight was much smoother and enjoyable. Sitting in small box floating in the air, it was strange feeling of freedom and helplessness, excitement and anxiety that hard to describe in words. Still occasional shake and slide of the plane would bring back the worst of fears. 

Friday, September 28, 2012

Oracle BPEL Engine (SOA Suite) Diagnostics - Parsing low level request stats

Parsing Low-Level Request Stats



This blog entry is in continuation to Francis blog entry http://thesoaman.blogspot.com/2012/06/using-bpel-performance-statistics-to.html which talks in detail about the use of low-level statistics provided by BPEL Engine of Oracle SOA Suite for diagnosing performance-related issues for projects involving BPEL processes. As promised to Francis, here are some details that might be useful while parsing the low-level request stats. Sorry took some time to put this out – better late than never!

As the request enters BPEL engine it is first handled by delivery service. This layer persists all incoming asynchronous requests are in the database. The request is then passed on to BPEL Engine (or generic name Cube Engine) for further processing.
Low-level request stats can provide insight into average taken by various engine layers (latency) as it flows through the delivery service and engine. The actual execution of request happens in invoke-method and the individual activity execution can be found by looking for stat with key actual-perform.

Wednesday, July 25, 2012

Golf Tournament - 5th SS Bajwa

Couple of years back (Aug, 2010) played my first Golf Tournament and playing with a partner we finished 3rd. It was 5th SS Bajwa Golf Tournament organized by Kang Brothers in memory of their late uncle. The tournament format was two man Scramble. Playing back tee and Flight A (handicap 12 or under), we shot 3 under 69. Tournament home page - http://www.ssbajwa.com/index.html
 



Monday, July 23, 2012

Good Magazine


A few years back I got introduced to Good Magazine during one of the Consumer Marketing class I took. Ever since I'm hooked on to this great magazine. In this blog entry, I'll review this magazine and outline what I like about it.

Good Magazine, henceforth referred to as GOOD (as they like to call them as), sets up their mission in their ‘about’ section on their website. It says and I quote “GOOD is a collaboration of individuals, businesses, and nonprofits pushing the world forward. Since 2006 we've been making a magazine, videos, and events for people who give a damn."
Further their website defines their magazine as following in a very powerful and no-nonsense manner:

In a world where things too often don’t work, GOOD seeks a path that does. Left, right. In, out. Greed, altruism. Us, them. These are the defaults and they are broken. We are an alternative model. We are the reasonable people who give a damn. No dogma. No party lines. No borders. We care about what works--what is sustainable, prosperous, productive, creative, and just--for all of us and each of us. This isn’t easy, but we are not afraid to fail. We’ll figure it out as we go.

BPEL SE (Java CAPS) Monitoring Console

The last major task I did during Sun days was the building of a new Monitoring console for the BPEL Service engine. It was a complete rewrite from scratch of the console to provide insight about running BPEL SE. Note that this product was not released as open-source as part of the project open-ESB. Anyway, was wanting to write a blog about it for a very long time, just did not sit down to do it. Working with the documentation group we prepared a user guide but was not able to found any online link to share (old Sun docs links have moved). Anyway, this blog would capture some of that.

The new monitor console is an independent web application that was developed using open JSF framework Icefaces (http://www.icesoft.org/) which provides rich ajax enabled components. It runs on Glassfish server in a Glassfish ESB environment. Here are some excerpts from the user guide:

The BPELMonitoring Console monitors your BPEL Service Engine's applications and business
processes, allowing you to quickly discern the health of your system. The console is designed to provide a comprehensive view of your current applications. It provides a real-time representation of your business processes throughout the life cycle of each instance. The console also enables you to drill down to see what is happening with any specific application or process. It allows you to track down a business process based on customer information and to suspend and resume an instance for system maintenance.
The BPEL Monitoring Console runs as an independent web application and can run from a
remote computer. The console runs on the Glassfish server in a GlassFish ESB environment.

Sunday, July 22, 2012

BPEL SE (Open-ESB) Scalability Support


Scalability Support for BPEL Service Engine

The complete solution for the scalability of system is co-coordinated work of all the constituent parts; service engines, binding components and NMR. When the system starts maxing out heap space, the full GC kicks in and ‘pauses’ the JVM. This has a debilitating effect on system performance. A properly designed system is expected to know the expected usage and provide enough resources for capacity utilization.

The specific problem in the context of business process orchestration involving interactions with external systems is the in-determinism in terms of responses for the outbound requests. When that happens the business process instances continue to hog memory and new requests for such processes would only aggravate the memory situation.

Since BPEL SE is the only component currently in the open-esb that can be configured to be used with a database, we can leverage this to provide scalability for long-running processes. Also, the BPEL SE scalability solution needs to be thought in conjunction with its recovery and monitor capabilities. In my opinion, the best solution is to have a very large heap space and nothing else would be required. But, if that cannot happen, at least with 32-bit boxes, and also for other reason s scalability solution as outlined here for BPELSE can help.

The scalability solution can be called in phases based on early detection and also following some patterns of business process behavior. The complete solution may be complex, but taking a trivial approach may not solve most (if not all) the use cases. Since the primary mechanism for the scalability solution of the BPEL Service Engine is passivation, there will be some overhead associated with that happens. Also, in order to minimize the overhead and not be overly aggressive about it, an attempt will be made to do the passivation in phases with each phase providing incremental relief.


BPEL SE (Open-ESB) Clustering Design


Architecture and Design Document of BPEL Service Engine Support for clustering & Failover


Clustering:

To achieve Scalability and High Availability for BPEL Service Engine running in JBI environment. A cluster is defined as a set of engines running in multiple JBI Environments running in Application Server Cluster. When a business process needs to be scaled to meet heavier processing needs, you can deploy Service Assemblies to BPEL Service Engine running on the application server cluster to increase throughput.

Failover:

To achieve transparent failover of running instances of the failed engine in cluster over to any live engine for continued processing.


BPEL Service Engine (Open-ESB)

Post oracle acquisition of Sun Microsystems, open source project Open-ESB has been end-of-lifed. There is no active development happening on Open-ESB core or components (the service engines or binding components). The project pages are also being moved around. To facilitate continued access to these pages, in next series of posts I will reproduce some pages or some of the features that I actively worked on, including but not limited to Clustering and Failover, Scalability and new monitoring console for BPEL Service Engine.

Understanding JavaScript Prototypal Inheritance for Java developers

Inheritance is a fundamental concept in programming languages. However, it is implemented differently in Object-Oriented Languages such as J...