Tuesday, September 29, 2020

Simple Progressive web application applications (PWA)

 Lets try to build now our own PWA application. For sake of knowledge we are using very simple page that display my image with few of my descriptions.

Lets create a simple html that dispaly image with some text and call it as index.html.

we will add few of the CSS to have its look and feel good.

Now let try to run the application on server. Many ways to do it. Either you can use the server extension of Google chorom or if you have node in stalled in your pc you can use serve . command.

As I am using VS code and its plugin “Open with live server” it will exposed our application on server localhost as shown below.

As we had added responsive behaviour you can see the site looks different when we change the browser width.

Now lets start to make our application as PWA.

As we stated PWA main part is to have a javascript know as service worker java script. we will create a file called as sw.js.

Additional PWA application provide us the facilities to add the shortcut of our application on mobile or desktop device this can be done by adding a file called as manifest.webmanifest.

manifest.webmanifest files contains information tag such as name, url, icons that is going to be displayed on the desktop etc.

Once this file is present in the project we can easily have the option of add to screen. When we try to open the google chorme developer tool F12 and see the application tab we will find that we did not get the add to home screen rather that it shows an error saying no matching service worker detected.

Above error is valid as still now we did not define any service worker javascript which is the core of PWA. Service workere JS reside in between application and you internet. sw.js is event driven means it get activated by firing event as an input and work accordingly.

Its main function is as follow

1- As a event driven it take event from user screen and work accordigly i.e either go to internet to fetch data or go to cache for the same.
2- As an intermediater between application and internet it will first cache all the items that we want it to cache and then if required call the internet for data.
3- It also has capaility to talk with server.
4- The main function it do is to call the internet to get the new data if the url is changed and deletet the old cache and fill with new data internet bring. If the internet is not there it will load the cache data to the user.
5- It will also store the whole form data in the cache so that whenever the internet come online data is submitted to the server and hence user did not have to fill the whole data again.
6- It also supopor the push mechanisum means it allows your applicatoin to get notification even though you are OFFLINE
7- It helps in auto sync means once the internet is on we can send the data from client to server automatically
8- It also support the functionality to access user device camera.
9- It also help to get the user location.

In our applicaiton we will try to implement following below items in sw.js

1- Event Driven function
2- Push
3- Sync

So lets create a sw.js file. In this files we will do following
//Install
//Activate
//Fetch

Lets try to understand what all above things in terms of development

//Install :- In this step we will check if the browser allows us to use the PWA functionality. If not we will show error to the end user.
//Activate :- In this step we will delete all the old cache and refill it with the new data that we get from the internet.
//Fetch:- Here we do following things
Step A:- Frist check if the internet is online. If online then we will make a call to server using internet and cache the new data.
Step B:- If no internet then show the result from the cache to the end users.

As shown below in sw.js we are doing following this sequence wise

//Define the cache name. By this name of the cache data is fetch when no internet is there.
const cacheName = 'siddhucache.1.0';
//This is the array that define the files that need to be cache
const staticAssets = [
    './',
    './index.html',
    './styles.css',
    './image/siddhu.jpg'
];

//Install :- This will be executed if site is accessed fresh or the version of the SW change. This is called immediately 
// Once the browser detect the new version of SW for registration. 
self.addEventListener('install', async e => {
    const cache = await caches.open(cacheName);
    await cache.addAll(staticAssets);
    //below line of code will tell start working as soon as request is made. 
    return self.skipWaiting();
});
//Activate :- In this step we will delete all the old cache and refill it with the new data that we get from the internet. This will 
// always be called once the user closed all the other browser instance and again install is called followed by Activate else it
// may create intrupt to the existing fucntionality/tab of the user.
self.addEventListener('activate', e => {
    //below line of code will tell old cache will be deleted and new will be created for new service worker.
    self.clients.claim();
});
//Fetch:- Here we do following things
//Step A:- Frist check if the internet is online. If online then we will make a call to server using internet and cache the new data.
//Step B:- If no internet then show the result from the cache to the end users.
self.addEventListener('fetch', async e => {
    const req = e.request;
    const url = new URL(req.url);

    if (url.origin === location.origin) {
        //below line indicate if the requested url is same and no internet then fetch the date from the cache
        e.respondWith(displayFirstCache(req));
    } else {
        //below line indicate else make a call to the internet and fetch the new data.
        e.respondWith(callNetworkFirstAndThenDoCache(req));
    }
});

//This fuction will be used to take the data from the cache defined in cacheName
async function displayFirstCache(req) {
    //Opening the cachee
    const cache = await caches.open(cacheName);
    //Matching the request
    const cached = await cache.match(req);
    //if same then return the cached else call the internet using fetch method.
    return cached || fetch(req);
}

//This fuction will be used to take the data from the internet and fill the new values in the cache defined in cacheName
async function callNetworkFirstAndThenDoCache(req) {
    const cache = await caches.open(cacheName);
    try {
        //calling internet and taking new data.
        const fresh = await fetch(req);
        //deleting the old cahce and pusing the new data.
        await cache.put(req, fresh.clone());
        return fresh;
    } catch (e) {
        //if no internet then use the old data.
        const cached = await cache.match(req);
        return cached;
    }
}

//this method is used to show the push notification to the user even though they are offline.
self.addEventListener('push', function (event) {
    console.log('[Service Worker] Push Received.');
    console.log('[Service Worker] Push had this data: "${event.data.text()}"');

    const title = 'Siddhu Push Notication comes';
    const options = {
        body: 'Push notification comes. This time it is from Chorme browser',
        icon: 'image/icon-192x192.png',
        badge: 'image/icon-512x512.png'
    };

    self.registration.showNotification(title, options);
});

//This method is used for having sync call between device and server. If the user fill the data on form and internet goes off and when
//the user again comes online at that time this sync is called. There is sync periodic Sync that run at definite interval of time.
self.addEventListener('sync', function (event) {
    if (event.tag == 'myFirstSync') {
        event.waitUntil(doSomeStuff());
    }
});
//Do the things which we want once the sync is on
async function doSomeStuff() {
    console.log("reached here")
}


Now as we have written our service worker java script we need to integrate it with our application. To do that lets add one more javascript file index.js

In this index.js we will fire the event driven command that will be taken by our sw.js

index.js:-

<!-- wp:paragraph -->
<p>window.addEventListener('load', () =&gt; {<br>registerSW();<br>syncButton()<br>});</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>async function registerSW() {<br>if ('serviceWorker' in navigator) {<br>try {<br>await navigator.serviceWorker.register('./sw.js');</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">} catch (e) {
  console.log('SW registration failed');
}</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>}<br>}</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>async function syncButton() {<br>try {<br>await navigator.serviceWorker.ready.then(function (swRegistration) {<br>return swRegistration.sync.register('myFirstSync');<br>});<br>} catch (e) {<br>console.log('SW registration failed');<br>}<br>}</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now check the site on browser F12 by doing both the option offline and online.</p>
<!-- /wp:paragraph -->

Offline Mode

Now lets try to execute push button

Note:- TO make the push button display on the screen go to below screen and mark allows

Now lets try for Sync functionality

Note:- You can download this applicatoin from the git hub
https://github.com/shdhumale/siddhupwaexample

you can also use the Lighthouse tab provided by the google to check how your applicaiton stands with PWA mark.


Benefits of PWA:-

1- Site can be loaded offline

2- Sync of data can be done as on when internet comes.

3- No new code development of Andriod, IOS and windows.

4- Work on Service Worker architecture hence on java script

5- Easily integrated with most of the sites written in any languages i.e pyhton, AngularJS, ReactJS, Vue or pyhton or anyother web technologies.

6- New tools like workbox support many new features like amount of cache, its life, 

7- Workbox provide simple yet sofisticated mehods for creating and integrating PWA in existing website.

8- It can be integrated at any stage i.e. already developed site, in mid of development or complete new site development.

9- Completly depends on developer and user to integrate what items need to be added in site i.e. cache, add to screen, push , sync, camera access, geolocation etc.

10- Facilities to integrate PWA on selected module of the application i,e, we can define to which module we want to have PWA customer module but not the payment modules.

11- No seperate installation of the application required in Andriod or IOS or Windows. Hence saving the space.

12- Adding the feature as you go. No hard and fast rule to add all the feature.

13- Service worker run on thread base and hence execution is non blocking and speedy.


Drawbacks of PWA:-

1- supported by most of the browser but not the supporting old browser like IE, edge and safari

2- Need to have the web application responsive in nature by default.


In next post we will try to use the better api for PWA using workbox.

Friday, September 25, 2020

PWA Progressive web application

 Nowadays web application development is not border by only web development. Today owner wants it to also work on device like mobile, tablet etc irrespective of its O/S andriod, Window or IOS.

In past, we used to speak and treat Web and mobile development in different ways i.e. we say andriod developers for device run on andriod, IOS developer for the device on MAC O/S same for windows. We use to treat Web development different from them.

Then come the age of responsive behaviour which with the help of new CSS tag like Media Query and now we can use the same code of web development to behave differently in terms of look and feel.

Then we move one more step above responsive i.e. we introduce PWA means we develope the site in web techonologies with belwo given benefits.

1- Our site work on offline mode. Yes I mean it OFFLINE mode without internet.
2- We do the cache of the data from the User UI Screen. i.e. we store the data that is inserted by the user UI or page that is shown to the user in cache.
3- We can do the Push mechanism from the server to the client when they come online.
4- We can do the sync process periodically or server defined on the user come online.
5- Highly low in size
6- Only need to know HTMLS5, CSS, JAVASCRIPT technologies.
7- Support all the latest browser that support HTML5 safari, chrome, firfox, opera etc. But not supported by IE.
8- No big size software installation on the device. you can store the browser url as an desktop icon and then reopen it as if it is like application installed. So no lose of storage.
9- Even the owner don't need to write and maintained different code for different device.
10-Google Chrome comes with excellent application in F12 or Developer tool that gives you in details about the PWA application options. Along with Lighthoues to test how your application is behaving as PWA.

Now lets try to understand little bit in terms of topology how its work

Device UI --> Service Worker JAVASCRIPT --> Cache --> Server

In general Service Worker JAVASCRIPT set in between the USer Device browser and internet. All the data that goes from the User Browser goes to internet goes from service worker. So where ever internet is not present this service worker js will store the data in cache.

And when ever the internet come online it service worker js will take the data from cache and send it to the server using internet.

Additional it gives notification and sync benefits to the user.

In next article we will show you how to creat a smile PWA application.

Thursday, September 24, 2020

How to solve the issues No cached version available for offline mode in Gradle.

By Default Gradle take the path c:\user\.gradle

but when you shared this .gradle folder to other user it will not be helpful to build the project in offline mode as it will give you
No cached version available for offline mode in Gradle

To over come this make sure to have your .gradle folder to be created our side your USER foler i.e. outside its default location c:\user\\

Let say If i want to share my .gradle folder to other machine that not connected to internet in that case  first build your project using internet for gradle and choose any folder other than default c:\user\
In my below example i am choosing gradle_home from my C folder to have .gradle folder

C:\siddhu\gradle_home

Once this is done share your gradle_home folder to the user not having internet and ask them to store the same in the package

i.e. c:\siddhu\gradle_home and click on offline check box to execute the build using offline mode.

Note:

You can also use the GRADLE_USER_HOME parameter to set on the Command prompt and run the gradle build --offline to build the project
Set GRADLE_USER_HOME=C:\siddhu\gradle_home\

Monday, September 14, 2020

Calling JCA Adaptor using Proxy and Pipeline in OSB

 Create a HTTP proxy and Pipeline as shown below

Drage Http to the proxy block

Join the Pipeline and Database JCA Adaptor as shown below

as you see we have error icon on the Procy so right click on it and click edit

Now run the proxy by right click and select run option and perform all the CRUD operation