Monday, July 20, 2015

MSCA/MWA Framework - Custom Development and Extension - Part 1

MWA Responsibilities, Menu and Functions

  • The way we create responsibilities, menus and functions is similar to other oracle applications.
Responsibilities:
  • Responsibilities should have "Oracle Mobile Applications" selected in "Available From".

Menu:
  • Menu are normally created with menu type "Standard".
Function:
  • Function should be created with type "Mobile Applications".

  • HTML Call of the function should point to java class full name for menu item bean (We'll discuss more on this in coming section.


Technical Overview of MSCA/MWA Framework

In technical overview of the MSCA/MWA Framework, we need to understand Mobile Application Beans (Mobile Application Screen UI Construction) and Event Listener Model (Event Handling like Page Enter, Field Exit, Button click etc):

Mobile Application Beans

Following are key Mobile Application Beans:
  1. oracle.apps.mwa.beans.MWABean
    • public class MWABean extends java.lang.Object implements java.io.Serializable
    • Base class for all UI beans.
    • MenuItemBean, PageBean, FieldBean, FlexfieldBean all extend from this class.
    • Maintains a list of MWA event listeners (protected java.util.Vector m_listeners).
      • public void addListener(MWAListener Listener)
      • public void removeListener(MWAListener Listener)
      • public java.util.Vector getListeners()
    • We don't use this bean directly in our coding.
    1. oracle.apps.mwa.beans.MenuItemBean
      • public class MenuItemBean extends MWABean
      • Connects FND Menu Structure to Mobile Application. FND Form function for the Mobile Application points to a MenuItemBean.
      • As per naming convention, MenuItemBean ends with suffix "Function".
      • It stores the key name of the first page of the mobile application (protected java.lang.String m_firstPageName).
        • public java.lang.String getFirstPageName()
        • public void setFirstPageName(java.lang.String FirstPageName)
        • Example - Following statement is typically written in the Constructor:
        • setFirstPageName("xxabc.oracle.apps.abc.xyz.inv.invtxn.server.MyFirstCustomPage");
        • FirstCustomPage is custom PageBean.
        • Other functions it provides are to set/get the menu confirmation message:
          • public void setMenuConfirmMessage(java.lang.String msg)
          • public java.lang.String getMenuConfirmMessage()
      1. oracle.apps.mwa.beans.PageBean
        • public class PageBean extends MWABean
        • Base class for all user developed page level beans.
        • Contains the page prompt which is displayed to the end user as the title of the page (protected java.lang.String m_prompt)
          • public void setPrompt(java.lang.String Prompt)
          • public java.lang.String getPrompt()
        • Maintains list of field beans which are part of this page (protected java.util.Vector m_fieldBeans) and current field indicator (protected int m_curtField):
          • public void addFieldBean(FieldBean FB)
          • public void addFieldBean(int index, FieldBean FB)
          • public void removeFieldBean(FieldBean FB)
          • public void removeAllFieldBeans()
          • public int getCurrentFieldIndex()
          • public int getFieldIndex(java.lang.String key)
          • public FieldBean getCurrentFieldBean()
          • public java.util.Vector getFieldBeanList()
          • public void setFieldBeanList(java.util.Vector BeanList)
        • Contains Session for the page (protected Session m_session) Session Handling methods:
          • public Session getSession()
          • public void setSession(Session sessionObject)
        • Other key methods:
          • To return the full name of the pagebean: public java.lang.String getName()
          • To mark if a page bean is to be instantiated upon each visit during runtime: public boolean isMultipleInstance(), public void setMultipleInstance(boolean MultipleInstance)
        • Typically as first step, we declare the FieldBeans in pageBean class's declaration section, and generate getters and setters for the fieldbeans. In Constructor to add field beans, modify fieldbean properties, change the order of the fieldbeans, associate field Listener to field beans (Details on FieldListener will be covered later).
          • For code examples - please refer FieldBean.
      1. oracle.apps.mwa.beans.FieldBean
        • public class FieldBean extends MWABean
        • Base class for all field level beans.
        • Important Subclasses - ButtonFieldBean, HeadingFieldBean, InputableFieldBean (With Subclasses - LOVFieldBean, MultiListFieldBean, TextFieldBean), ListFieldBean, MessageFieldBean.
        • Maintains name property of the field (protected java.lang.String m_name)
          • public java.lang.String getName()
          • public void setName(java.lang.String Name)
        • Maintains prompt property of the field (protected java.lang.String m_prompt)
          • public java.lang.String getPrompt()
          • public void setPrompt(java.lang.String Prompt)
        • Maintains hidden property of the field (protected boolean m_hidden)
          • public boolean isHidden()
          • public void setHidden(boolean Hidden)
        • Maintains type of field (protected short m_type):
          • default is INPUTTEXT.
          • public int getType()
          • Possible Values include:
            • public static short TEXT
            • public static short LOV
            • public static short MULTILIST
            • public static short LIST
            • public static short BUTTON
            • public static short CHECKBOX
            • public static short RADIO
            • public static short HEADING1
            • public static short HEADING2
            • public static short LINESEPARATOR
            • public static short SPACESEPARATOR
            • public static short MENUITEM
            • public static short RESPONSIBILITYITEM
            • public static short LOVRUNTIMEITEM
            • public static short MULTILISTRUNTIMEITEM
            • public static short DESCFLEX
            • public static short KEYFLEX
            • public static short SEGMENTLOV
            • public static short SEGMENTTEXT
      1. oracle.apps.mwa.beans.FlexFieldBean
        • public class FlexfieldBean extends MWABean implements oracle.apps.fnd.flexj.event.FlexfieldListener
        • It represents the flexfield in the Mobile Applications
        • Constructor - public FlexfieldBean(oracle.apps.fnd.flexj.Flexfield flexfield, oracle.apps.mwa.container.Session session)
        • Maintains boolean variables and getters and setters for readonly, hidden and required (private boolean m_readonly, m_hidden, m_required):
          • public boolean isRequired()
          • public void setRequired(boolean requiredFlag)
          • public void setHidden(boolean hiddenFlag)
          • public void setReadonly(boolean readOnlyFlag)
          • public boolean isReadonly()
        • Important Flexfield related APIs:
          • public Flexfield getFlexfield()
          • protected boolean addSegmentBean(Segment Seg)
          • protected void removeSegmentBean(Segment Seg)

      Following are three most frequently used beans on Mobile Application Pages:
      1. oracle.apps.mwa.beans.TextFieldBean
        • public class TextFieldBean extends InputableFieldBean
        • Constructor: public TextFieldBean()
        • Frequently used properties and their getters and setters inherited from FieldBean:
          • name, prompt, hidden
        • Frequently used properties and their getters and setters inherited from InputableFieldBean:
          • editable (protected boolean m_editable)
          • required (protected boolean m_required)
          • display length (protected int m_length)
          • value (protected java.lang.String m_value)
          • value type (protected java.lang.String m_valueType)
            • Possible values are: S - String, N - Number, D - Date, C - Calculation, R - Range
        • Maintains password property (protected boolean m_password)
          • public boolean isPassword()
          • public void setIsPassword(boolean IsPassword)
        • Maintains navigation to next page property (protected java.lang.String m_nextPageName)
          • public java.lang.String getNextPageName()
          • public void setNextPageName(java.lang.String NextPageName)
      2. oracle.apps.mwa.beans.LOVFieldBean
        • public class LOVFieldBean extends InputableFieldBean
        • Constructor: public LOVFieldBean()
        • Frequently used properties and their getters and setters inherited from FieldBean:
          • name, prompt, hidden
        • Frequently used properties and their getters and setters inherited from InputableFieldBean:
          • editable, required, display length (length), value, value type
        • Maintains navigation to next page property (protected java.lang.String m_nextPageName)
          • public java.lang.String getNextPageName()
          • public void setNextPageName(java.lang.String NextPageName)
        • Maintains LOV Statement (protected java.lang.String m_lovStatement)
          • This is mandatory to be set.
          • Store SQL query or PL/SQL procedure with a reference cursor output parameter.
          • public void setlovStatement(java.lang.String LovStatement)
          • public java.lang.String getlovStatement()
        • Maintains key names, prompt, types, rendered property of the subfields of the Lov page,  (protected java.lang.String[] m_subfieldNames, protected java.lang.String[] m_subfieldPrompts, protected java.lang.String[] m_subfieldTypes, protected boolean[] m_subfieldDisplays ).
          • The size of these arrays should be same.
          • public java.lang.String[] getSubfieldNames()
          • public void setSubfieldNames(java.lang.String[] SubfieldNames)
          • public java.lang.String[] getSubfieldPrompts()
          • public void setSubfieldPrompts(java.lang.String[] SubfieldPrompts)
          • public java.lang.String[] getSubfieldTypes()
          • public void setSubfieldTypes(java.lang.String[] SubfieldTypes)
          • public boolean[] getSubfieldDisplays()
          • public void setSubfieldDisplays(boolean[] SubfieldDisplays)
        • Maintains key names of the input parameters and parameter types (protected java.lang.String[] m_inputParameters, protected java.lang.String[] m_inputParameterTypes)
          • public java.lang.String[] getInputParameterTypes()
          • public void setInputParameterTypes(java.lang.String[] InputParameterTypes)
          • public java.lang.String[] getInputParameters()
          • public void setInputParameters(java.lang.String[] InputParameters)
        • Maintains values returned from LOV or selectec values (protected java.util.Vector m_selectedValues)
          • public java.util.Vector getSelectedValues()
          • public boolean isPopulated()
        • Maintains lov validation required property (protected boolean m_validateFromLOV)
          • Specifies if user has to always go through LOV page - if false, value in the field is accepted without validation.
          • Default is True.
          • public void setValidateFromLOV(boolean validateFromLOV)
          • public boolean isValidateFromLOV()
      3. oracle.apps.mwa.beans.ButtonFieldBean
        • public class 
          ButtonFieldBean
           extends FieldBean
        • Constructor: public 
          ButtonFieldBean
          ()
        • Frequently used properties and their getters and setters inherited from FieldBean:
          • name, hidden (behavior of prompt is different for buttons as it includes accelerator keys)
        • Maintains button prompt property with accelerator key (protected java.lang.String m_prompt):
          • public void setPrompt(java.lang.String s)
          • public void setPrompt(java.lang.String s)
          • If we call setPrompt("&Done"), getPrompt() will return "Done".
            • 'D' will be the hot key for "Done" button
        • Maintains navigation to next page property (protected java.lang.String m_nextPageName)
          • public java.lang.String getNextPageName()
          • public void setNextPageName(java.lang.String NextPageName)
        • Maintains accelerator key enable/disable property (protected boolean m_enableAcceleratorKey)
          • public void setEnableAcceleratorKey(boolean b)
          • public boolean isAcceleratorKeyEnabled()

      Oracle MSCA/MWA Framework - Introduction

      MSCA

      • Stands for Mobile Supply Chain Application.
      • MSCA is for staff in warehouse, shop floor, most of whom are always on the move.
      • MSCA trasactions are carried out from hand-held devices.
      • To efficiently operate and infuse visibility in the system - RFID (Radio Frequency Identification) readers are used by warehouse/shop floor staff to read barcodes and use them in transactions.
      • Items, Locators, Sub-Inventories etc are barcoded and these barcodes are not entered manually but scanned with the handheld devices while performing transactions thus providing efficiency, speed as well as accuracy.

      MWA

      • Stands for Mobile Web Application.
      • MWA is telnet based application that runs on internet (WIFI and GPRS) based wireless devices.
      • Telnet client is configured on the handheld device, for testing it is used on desktop.
      • MWA Applications are based on Java.
      • MWA is part of WMS (Warehouse Management System).

      MWA Architecture:




      Fortunate enough to get a chance to closely observe and experience warehouse transactions using handheld devices. Typical work on MWA Applications:
      • Development of custom screens for handheld devices.
      • Extend the existing MWA screens.
      • Personalize existing MWA screens.

      Technical Skills Required:
      • Java
      • PLSQL 
      • XML
      Softwares Required:
      • JDK to be installed in system.
      • Mobile Wireless Applications (MWA) J2ME Telnet GUI Client. 

      Navigation

      Navigation on mobile device uses "Enter" key.
      "Enter" key will fire fieldExited event.
      Whenever we scan a barcode, barcode will populate the value and there is an associated "Enter" key for navigation to next field.

      Key Mappings
      • Key mappings are visible on mobile help screen on pressing "F1" (Standard key for Help).
      Following are standard key mappings:

      Shortcut Key Purpose
      F1 Help
      F2 Menu
      F3 Back
      F4 Forward
      Ctrl K Clear
      Ctrl L LOV
      Ctrl M Responsibility Menu
      Ctrl B Long Description of status message
      Ctrl Z Toggle between options in a list field
      Ctrl A Show Current Field on page
      ESC For Hot Keys
      Ctrl Z Toggle between options in a list field
      Ctrl D Page Up
      Ctrl C Page Down
      Ctrl G Generate (Generate Serial Number etc)
      Ctrl S Skip Task on Task Page
      Ctrl X About Page
      Ctrl F Open Flexfield Window


      MWA Configuration

      • $INST_TOP/admin/install/mwa.cfg stores the MWA configuration.
      • Following are the key configuration variables in this file:
        • mwa.DbcFolder
        • mwa.DbcFile
        • mwa.logdir
        • mwa.LogLevel
        • mwa.SystemLog
        • mwa.EnableLogRotation
        • mwa.MaxLogFileSize
        • mwa.SubmenuChangeOrgResp
      • Refer to MSCA Implementation Guide> MWA Server Setup > MWA Configuration File for more details.
      • Key mappings can be modified for a particular device ($INST_TOP/admin/install/Device IP.ini) or all devices ($INST_TOP/admin/install/default_key.ini). (Refer to MSCA Implementation Guide> MWA Server Setup > Key Mappings).  
      Steps to Configure MWA Client:
      • MWA Client needs to confirmed 
      • Search for "Mobile Wireless Applications (MWA) J2ME Telnet GUI Client" or "Latest MWA GUI Client" etc on oracle support. Latest patch that I found and tried was 12780257. Patch "Read me" file contains details on patch installation.
      • https://support.oracle.com/epmos/main/downloadattachmentprocessor?parent=DOCUMENT&sourceId=294670.1&attachid=294670.1:1&clickstream=yes

        MWA Administrator

        • Standard MWA responsibility for MWA for Mirroring and Sending message to another mobile device for communication.
        Mirroring Mobile Session
        • MWA Administrator > Telnet Session Monitor can be used to mirror an active session of another user.
        • Both users must be on the same MWA Server.
        • This can greatly help in debugging and supporting MWA Applications.
        Send Message
        • MWA Administrator > Send Message can be used to send a brief message to another user.
        • Both users must be on the same MWA Server.
        • User will see the message on any key press.
        • After pressing OK, user can continue with their transaction.

        Starting/Shutting MWA Server

        • Location of Scripts - cd $INST_TOP/admin/scripts
        • Start Command - mwactl.sh start [port number]
          • Ex. mwactl.sh start 6060
        • Shutdown Command - mwactl.sh-login xxx/yyy stop/stop_force [port number]
          • mwactl.sh -login cbaker/welcome stop 6060
          • mwactl.sh -login cbaker/welcome stop_force 6060

        Hardware devices typically used:

        • Barcode Printer
        • Ribbon for barcode printing
        • Rugged/Semi-rugged mobile devices
        • lamination labels

        Please proceed to MSCA/MWA Framework - Custom Development and Extension - Part 1 to read more on custmization in MSCA/MWA Framework.

        Please proceed to MSCA/MWA Framework - Mobile Personalization to read more on Personalizing standard MSCA/MWA Screens.

        Tuesday, January 14, 2014

        Responsive Web Design



          • Designing webpages in a way that webpage adapts to the visible area (Width and Height) of the screen. 
          • Page layout should expand or shrink smoothly and alter itself to optimize and enhance the user experience.
          • Term "Responsive design" is generally used in the context of mobile devices but responsive design also covers wide screen devices like Smart TV and Gaming Consoles.
            • There is possibility of size related issued in wide screen devices, so that should also be considered.
          • Earlier web pages were mostly being viewed in desktops but the same is not true today. Today we don't know the size of the device where our webpage will be viewed. Thus the need for webpages to be designed for various screen sizes and browsers.
          • Adaptability is the buzz word for Responsive Design.

          Focus on more than just Phablets

          • Different UI Device sizes - 
            • Smartphones
            • Tablets
            • Desktops
            • Wide Screen Smart TVs and Gaming Console

          Mobile First Design Approach

          • Its a good practice to design first for the mobile in a linear manner and then organize the widgets for wider screens.
          • Designing for the mobile environment comes with a natural set of constraints.
          • These constraint provides the much needed focus and are good for the overall User Experience.

          Importance of Unlearning

          We need to forego outdated information and learn new age knowledge.
          • Earlier TV used to be called Radio with pictures. Radio programs are supplemented with running commentary because expressions, movement of actors was not visible. Older TV programs also used to be supplemented with running commentory though not needed.
          • Traditionally designing was always done for a constraint canvas whether it is - 
            • Cave Painting (where cave wall was our canvas)
            • Stone sculpture (where stone was the canvas)
            • Painting 
            • Newpaper Design
            • Business Card Design
            • Wedding Card Design (list is endless).
          • Even most of the webpages were designed with desktops in mind.

          A Not that Good Solution Approach

          • Device Experience
            • Having different website for mobile and desktops:
            • It doesn't address the problem of adaptability.
            • We are still applying constraints on our design.
            • URLS cannot be shared between devices.
            • Doesn't address the landscape and portrait layouts on the mobile devices.

          Related Points to remember

          • Mobile Users Deserve the Same Quality of Browsing Experience. 
          • A simple HTML file in a web browser automatically adapts to fit the width of that browser. We have been breaking the responsiveness of the web over the years by designing to constraints.
          • Mobile browsers have the ability to take the full-size webpage and scale it to fit on the browser's screen. This gives users the ability to pinch and zoom in order to read it.
            • The idea for responsive design is that user should not be doing pinch and zoom to read it, content should get rearranged for the optimal user experience.
          • Hover can't be used on Smartphones and many other devices, thus special care is needed while designing websites relying on Hovers.
            • Most touch devices activate the hover state on tap.
          • There is a need to ensure sufficient spaces between the two actions (navigations/buttons etc), this is needed to ensure that user could easily tap with the fingers.
          • Font Selection, Menus, Links should also consider different devices.
          • If the requirement is not to expand or shrink the image with the window size but just reducing the width of the image by hiding the overflow the image, then consider using background image.

          Steps to Responsive Design

          • Responsive design uses feature detection (mostly on the client) to determine available device capabilities and adapt accordingly.
          • Responsive design is achieved with a combination of following to change layout based of the size of the viewport:
            1. Flexible Grids,
              • As much as possible use proportions for measurement and never design for a fixed layout.
              • Width, Font size also should be relative (width in percentage and Font Size in ems).
              • Margins, Padding should also be relative.
            1. Flexible Images and Media,
              • Width of images should always be entered and needs to be relative.
              • Max-Width should be set to 100%.
                • Wide images overflow out of the containing window if the size is reduced. "Max-Width" prevents the value of width property from becoming larger than max-width.
                • With max-width property set, img element will render at whatever size it wants, as long as it’s narrower than its containing element. 
                • It gives us floating image.
                     img,

                     embed,
                     object, 
                    video { 
                  max-width: 100%;
                  height:auto;
                  // To ensure the image is not getting distorted. 
                     }
                • If we wish to hide the excess image data, we can also use "overflow:hidden".
            1. Media Queries
              • Media Queries is a CSS3 module allowing content rendering to adapt to conditions such as screen resolution (e.g. smartphone vs. high definition screen).
              • It is cornerstone of Responsive Web Design.
              • It is an improvement on CSS2 Media Types, which allowed us to provide different CSS properties for different media types, thus allowed us to control the document presentation on different devices.
                • Refer to W3C specification for more details.
                • Different Media Types - all, braille, embossed, handheld, print, projection, screen, speech, tty, and tv.
                • Example -
                  • <link rel="stylesheet" href="main.css" media="screen" />
                  • @media screen {
                        .container {
                            width: 90%;
                        }
                    }
                  • @media handheld {
                        body {
                            font-size: 110%;
                        }
                    }
                • Media types were first towards in the direction of Responsive Design but not sufficient for Responsive Design thus came Media Queries.
              • Media Queries are used to customize CSS for specific types of media, inspecting the physical characteristics of the devices and browsers.
              • Following are the two components of Media Queries:
                • Media Type
                • Condition comparing a feature to a value in parenthesis. 
                  • We can have more than one condition linked with And/Or etc.
                  • Popularly used to compare width but other features like height, device-width, device-height, orientation, aspect-ratio, device-aspect-ratio, color, resolution, scan etc.
                  • Examples:
                  • <link rel="stylesheet" href="style_screen_wide.css" media="screen and (min-width: 960px)" />
                  • @import url("style_screen_wide.css") screen and (min-width: 960px);
                  • @media screen and (min-width: 960px) {
                        .container{
                           width : 90%;
                        }
                    }
                  • @media screen and (min-device-width: 480px) and (orientation: landscape)
            1. Viewport Meta Tag
              • Term 'Viewport' refers to window of the browser.
              • Used along with Media Queries to control the responsive design.
              • Mobile browsers have the ability to take the full-size webpage and scale it to fit on the browser's screen. The default window size of the page is taken as 980px and then browser scales it to the mobile's width.
                • This is because before responsive design became popular, the expectation was to get fix-width desktop experience on mobile device.
                • To overcome this Apple introduced the viewport meta tag, most others adopted this but its still not a standard from w3c.
              • Viewport metatag is placed inside the head and is used to control the scale of the page.
              • Viewport tag allows us to control the size of that canvas, and override that default behavior.
              • Examples -
                • <meta name="viewport" content="width=320" />    //  Bad Idea because of hardcoding width to 320px.
                • <meta name="viewport" content="initial-scale=1.0, width=device-width" />     //  setting the width to 100% of the width of device.
                • Initial scale means default view is without zoom, we could also set the max-scale if we wish to disable (value = 1) or restrict the feature of pinch and zoom to 200% or any other value.
              1. Breakpoints
                • On altering the screensize(growing or shrinking), we'll reach a point where the layout design will get altered to suite this new size like rearranging of fields, shift from 3-column layout to  2-column or stack, Font sizes will reduce etc.
                • How many breakpoints and where to set them depends on the website, but there are few tools which can help in this. Ex. web developer extension from chrispederick.
                • Examples -
                  • <480px  - Smaller smartphone screen sizes
                  • <768px  - Larger smartphones and smaller tablets
                  • >768px  - Large tablet screens and desktops screens.
                  • <320px  - Low resolution phones and other devices like barcode reader
                  • >1024px - Wide screens devices

              Cross Browser Testing Tools

              •  There are many services for performing cross-browser testing, following are few examples:
                • browserstack.com
                • crossbrowsertesting.com

              Support for Older Browsers

              •  Following are helpful when it comes to support HTML5 and CSS 3 features in older browsers:
                • caniuse.com
                • modernizr
                • html5shiv
              • There are many JS based solutions available for HTML5 and CSS3 features not available in older browsers.

              Some Words of Caution

              • Most responsive websites take more time to load.
                • A responsive website deliver large amounts of code (which is even more when a RWD framework is used) irrespective of the device.
                • Processing power/Rendering capabilities of a smartphone are much lower than the desktop, the amount content/data/code greatly impacts the rendering time.
                • Compress page resources (using GZIP etc) for easier transmission across networks is a good practice.
                • Modular/Multiple css files are very convenient for development but not ideal scenario for deployment. Using CSS Preprocessor like SASS, LESS etc help in easy management of CSS during development as well as production.
                • Reducing the image sizes using tools like tinypng can reduce data transmission. 
                • Using service like adaptive-images.com, which detects your visitor's screen size and automatically creates, caches, and delivers device appropriate re-scaled versions of your web page's embeded HTML images.
                • A Content Delivery Network (Network of various servers to serve content at various locations to reduce network time) for Static Content can improve performance.
                • Using a Content Management System can also help in improving performance. 

              Few Popular examples of Responsive Websites:

              1. Time.com
              2. living.is
              3. Expedia.com

               

               

              Key Terms

              • Adaptive Design
                • Another term for RESS.
              • Breakpoint
                • On altering the screensize(growing or shrinking), we'll reach a point where the layout design will get altered to suite this new size like rearranging of fields, shift from 3-column layout to  2-column or stack, Font sizes will reduce etc.
              • Device Experience
                • Design strategy with different websites for each device. It is used for maximum optimization for each type of device.
              • Display Area
                • Browser's viewport.
              • Media Type
                • First Attempt at the responsive design, part of CSS2 specification. 
                • HTML 4 and CSS2 currently support media-dependent style sheets tailored for different media types.
                • Created by W3C for classifing each browser or device under a broad, media-specific category. 
                • The recognized media types are: all, braille, embossed, handheld, print, projection, screen, speech, tty, and tv.
              • Media Query
                • Media queries extend the functionality of media types by allowing more precise labeling of style sheets
                • A media query consists of a media type and zero or more expressions that check for the conditions of particular media features. Among the media features that can be used in media queries are 'width', 'height', and 'color'. By using media queries, presentations can be tailored to a specific range of output devices without changing the content itself.
              • Multi-Channel / Omni Channel
                • In simple terms - Multi-Device
                • Refers to multiple channels to content delivery - Smart Phones, Tablets, Desktop, Wide Screen Devices etc.
              • Rendering Surface
                • Entire display of the device.
              • RWD
                • Responsive Web Design
              • Viewport
                • Window of the browser.
                • It has nothing to do with the device.

                What Next ? - RESS

                • Responsive Design with Server Side components.
                • Also referred to as "Adaptive Design".
                • This is second generation of RWD which takes performance into account. [Refer to related section - Some Words of Caution]
                • RESS can deliver the best of "Responsive Design" and "Device Experience" without the challenges that can hamper each. 
                  • Server will deliver code and content based on the client device allowing responsive website to load much faster on different devices.
                  • Server-side techniques include user agent detection, server-side breakpoints, and robust server-side feature detection.
                • Feature Detection vs Device Detection
                  • Feature detection framework runs a test in the browser to get a boolean answer as output: "Is X Supported?" and the answer is mostly "true" or "false".  It works on all browsers (current and future). Ex Modernizr.
                  • Device Detection framework analyses the HTTP header of the device, to get information about the device, then gets capabilities for that device from a database maintained for this purpose.
                • Cookie can be used to share the information between client and Server.

                Monday, December 30, 2013

                A short guide to JSON - JavaScript Object Notation

                JavaScript Object Notation

                • Lightweight, open standard, human-readable, language/platform independent and self-describing text-based designed for storing and transferring structured data.
                • This format was specified by Douglas Crockford. <LINK>
                • JSON Internet Media type is application/json.

                Use Cases:

                • Serializing and transmitting structured data over network connection.
                • Web Services and API's use JSON format to provide public data.
                • Fetch JSON data from a web server, convert it to a JavaScript object, use it to manipulate the UI.

                Advantages:

                • Easy for computers and humans to read and write.
                • Supports tree like Hierarchies in data.
                • Can be easily mapped to data structures used by most programming languages (numbers, strings, booleans, nulls, arrays and associative arrays).
                • Most programming languages support JSON.

                Limitations:

                • Capable of representing numbers, booleans, strings, null, and arrays and objects. Doesn't natively support complex data types like functions, regular expressions, dates etc.
                • Doesn't have a widely accepted schema for defining and validating the structure of JSON data.

                Syntax:

                • JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values.
                • JSON defines six data types: string, number, object, array, true, false and null.
                • Objects are enclosed in braces ({}).
                • Name and value in a pair are separated by a colon (:). 
                • Name-Value pairs are separated by a comma (,).
                • Names in an object are strings, whereas values may be of any of the six data types, including another object or an array.
                • Arrays are enclosed in brackets ([]), and their values are separated by a comma (,).
                • Each value in an array may be of a different type, including another array or an object.

                JSON Example:

                var emptyObj = {};

                var empObj = {eid: '7918', ename: 'Prince', grade: 'T3'};
                 
                {
                "empObjs": [
                                   { "eid":"7918" , "ename":"pkapoor", "grade":"T2" },
                                   { "eid":"709" , "ename":"jai", "grade":"T4" },
                                   { "eid":"13386" , "ename":"rahul", "grade":"T3" }
                                   ]
                }

                Deserialize JSON 

                • Javascript eval() and JSON Parsor:
                    <script>
                    
                    var txt = '{"empObjs":[' +
                        '{"eid":"7918","ename":"pkapoor" },' +
                        '{"eid":"709","ename":"jai" },' +
                        '{"eid":"13386","ename":"rahul" }]}';

                        var obj = JSON.parse(txt);
                        // var obj = eval ("(" + txt + ")");
                        document.getElementById("eid").innerHTML=obj.employees[1].eid         document.getElementById("ename").innerHTML= obj.employees[1].ename     </script>

                Serialize JSON 

                • JSON Stringify
                  • JSON.stringify() outputs JSON strings with all whitespace removed. It makes it more compact for sending around the web.
                        /* Put this line in above example and print the value. */
                        var text = JSON.stringify(obj);

                JSON vs XML

                • JSON is smaller than XML, faster, easier to parse and more human readable format.
                • XML is more verbose than JSON, so it's faster to write JSON for humans.
                • JavaScript's eval method parses JSON. When applied to JSON, eval returns the described object.
                • The Ajax (Asynchronous JavaScript And XML) originally used XML to transmit data between server and browser, but now JSON has become a more popular way to carry Ajax data.
                • XML is a tried-and-tested technology and is used in a huge range of applications.
                • Doesn't have a widely accepted schema for defining and validating the structure of JSON data.

                JSON and Java

                Java APIs for JSON processing are easily available and easy to use..
                javax.json package - contains reader, writer, model builder interfaces for the object model along with other utility classes and Java types for JSON elements.
                javax.json.stream package - contains a parser interface and a generator interface for the streaming model.
                Refer to http://docs.oracle.com/javaee/7/tutorial/doc/jsonp001.htm for more details.

                JSON and AJAX

                The Ajax (Asynchronous JavaScript And XML) originally used XML to transmit data between server and browser, but now JSON has become a more popular way to carry Ajax data.

                For Further Reading:

                JSONPath
                JXON
                JSON-LD

                Reference

                http://docs.oracle.com/javaee/7/tutorial/doc/jsonp001.htm#BABEECIB
                http://www.json.org/js.html
                http://www.youtube.com/watch?v=wbB3lVyUvAM

                Friday, November 22, 2013

                Java Virtual Machine - Loading, Linking and Initializing

                Loading

                • Process of finding the binary representation of a class or interface type with a particular name and creating a class or interface from that binary representation.
                • (JVM Specification: ) Java Virtual Machine specification gives implementations flexibility in the timing of class and interface loading.
                • Internal data structures are populated including Method area.
                • An instance of class java.lang.Class for the class being loaded is created.
                • Information about a type that is stored in the internal data structures and accessed by invoking methods on the Class instance for that type.
                • If Class Loader encounters a problem, it is reported during linking phase (LinkageError) on first active use of the class.

                Linking 

                • A class or interface is completely loaded before it is linked. 
                • Process of taking a class or interface and combining it into the run-time state of the Java Virtual Machine so that it can be executed.
                • Linking a class or interface involves verifying and preparing that class or interface, its direct superclass, its direct superinterfaces.
                • Dynamic linking involves locating classes, interfaces, fields, and methods referred to by symbolic references stored in the constant pool, and replacing the symbolic references with direct references.
                • Linking is divided into three sub-steps: verification, preparation, and resolution:
                  • Verification ensures the type is properly formed and fit for use by the Java Virtual Machine.
                    • Verification ensures that the binary representation of a class or interface is structurally correct.
                    • Verification may cause additional classes and interfaces to be loaded but need not cause them to be verified or prepared.
                    • Final classes/methods, abstract classes/methods validations are checked here.
                  • Preparation involves allocating memory needed by the type, such as memory for any class variables.
                    • Involves creating the static fields for a class or interface and initializing such fields to their default values (initializing to other values except default values is done in Initialization where explicit initializers are executed).
                  • Resolution is the process of transforming symbolic references in the constant pool into direct references. 
                    • It is an optional part of linking.
                    • Implementations may delay the resolution step until each symbolic reference is actually used by the running program.
                    • After verification, preparation, and (optionally) resolution are completed, the type is ready for initialization. Resolution, which may optionally take place after initialization.
                • (JVM Specification: ) Java Virtual Machine specification gives implementations flexibility in the timing of class and interface linking.

                Initialization

                • Initialization of a class or interface consists of executing the class or interface initialization method <clinit>.
                  • <clinit> is static and has no arguments and is for static initialization blocks.
                  • If there is no initialization of class variables in the code, compiler will not generate <clinit> method
                • Class variables are initialized during Initialization phase.
                • Initialization of a class or interface requires careful synchronization, since some other thread may be trying to initialize the same class or interface at the same time.
                • (JVM Specification: ) All implementations must initialize each class and interface on its first active use.
                • Involves creating the static fields for a class or interface and initializing such fields to their default values (initializing to other values except default values is done in Initialization where explicit initializers are executed).

                Class-In-Use (Working with Objects)

                • For each constructor in the source code of a class, the Java compiler generates one <init() method.
                • If the class declares no constructors explicitly, the compiler generates a default no-arg constructor that just invokes the superclassís no-arg constructor.
                • For every class except Object, an <init() method must begin with an invocation of another <init() method belonging either to the same class or to the direct superclass.
                • Instance initialization methods may be invoked only by the invokespecial instruction (§invokespecial), and only on uninitialized class instances.

                Unloading Class

                • Java Virtual Machine will run a class's classFinalize() method (if the class declares one) before it unloads the class.
                • If the application has no references to the type, then the type can't affect the execution of program and it can be garbage collected.

                Class Loader

                • At run time, a class or interface is determined by a its binary name and defining class loader both.
                • Class Loader deals with file system to load the files for the JVM, no other component in JVM needs to deal with file system.
                • All Java virtual machines include one class loader that is embedded in the virtual machine, called Primordial class loader.
                • Every Class object contains a reference to the ClassLoader that defined it.
                  • Class.getClassLoader()
                • Class LoaderTestClass loaded by class loader A, is not the same class as the class LoaderTestClass loaded with class loader B.
                • There are following three types of class loaders:
                  • Bootstrap Class Loader
                  • System Class Loader
                  • Extension Class Loader

                Premordial (Bootstrap) Class Loader

                • It implements the default implementation of loadClass().
                • Written in native language.
                • JVM assumes that it has access to a repository of trusted classes which can be run by the VM without verification.
                • Java core API classes are loaded by the bootstrap (or primordial) Class Loader.
                • Bootstrap ClassLoader searches in the locations (directories and zip/jar files) specified in the sun.boot.class.path system property.
                  • String bootClassPath = System.getProperty("sun.boot.class.path");
                • Types loaded through the primordial class loader will always be reachable and never be unloaded.

                Application (System) Class Loader

                • Application-specific classes are loaded by the system (or application) ClassLoaders.
                • Our application's code is loaded using this.
                • The system ClassLoader searches for classes in the locations specified by the classpath (set as the java.class.path system property) command-line variable passed in when a JVM starts executing. 
                  • String appClassPath = System.getProperty("java.class.path");
                  • sun.misc.Launcher$AppClassLoader

                Extensions Class Loader

                •  Loads the code in the extensions directories (<JAVA_HOME>/jre/lib/ext, or any other directory specified by the java.ext.dirs system property).
                  • String extClassPath = System.getProperty("java.ext.dirs");
                  • sun.misc.Launcher$ExtClassLoader

                Custom (User-Defined) Class Loader

                • Subclass of the abstract class Java.lang.ClassLoader
                • Method loadClass is to be implemented.
                  • loadClass should be synchronized.
                  • Call findLoadedClass to check class is already loaded. 
                  • If we have the raw bytes, call defineClass to turn them into a Class object.
                  • If the resolve parameter is true, call resolveClass to resolve the Class object.
                  • If class not found, throw a ClassNotFoundException.
                • Every loaded class needs to be linked. This is done using the ClassLoader.resolve() method. This method is final.
                • Following are the steps a class loader performs:
                  • Check if the class was already loaded.
                  • If not loaded, ask parent class loader to load the class. 
                  • If parent class loader cannot load class, attempt to load it in this class loader.

                Examples of Class Loaders:

                • java.net.URLClassLoader, 
                • java.security.SecureClassLoader

                Related Terms and Concepts:

                JVM Startup

                • The Java Virtual Machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader.
                • The Java Virtual Machine then links the initial class, initializes it, and invokes the public class method void main(String[]). 
                • In an implementation of the Java Virtual Machine, the initial class could be provided as a command line argument. Alternatively, the implementation could provide an initial class that sets up a class loader which in turn loads an application. 

                JVM Dynamic Linking

                • The process of JVM loading your program's classes and interfaces and hooking them together.
                • Java Virtual Machine builds an internal web of interconnected classes and interfaces.

                Binding

                • Binding is the process by which a function written in a language other than the Java programming language and implementing a native method is integrated into the Java Virtual Machine so that it can be executed.
                • Although this process is traditionally referred to as linking, the term binding is used in the specification to avoid confusion with linking of classes or interfaces by the Java Virtual Machine. 
                Previous: Java Virtual Machine - Garbage Collection

                Tuesday, November 12, 2013

                Java Virtual Machine - Garbage Collection


                • Garbage Collection is not restricted to Java, its a generic concept that applies to most of the programming languages.
                • Garbage collection is the process of automatically freeing objects that are no longer referenced by the program. 
                • The garbage collector must determine which objects are no longer being referenced by the program.
                • Garbage collector must run any finalizers of objects being freed.
                • Garbage collection is automatic, thus it removes the possibility of developer errors due to incorrectly freeing of memory.
                • Runtime.gc() and System.gc() only suggests JVM to run Garbage Collection, it is not mandatory that Garbage Collection will definitely run after call to these methods.
                • Java virtual machine has an instruction that allocates memory on the heap for a new object (created in source coce), but has no instruction for freeing that memory.
                • Garbage Collection in Java is carried by JVM's  daemon threads for Garbage Collection.
                • Garbage collection was invented by John McCarthy around 1959 to solve problems in Lisp.

                Java provides many garbage collectors, following are some examples:

                • Parallel Scavenge
                • Serial Garbage Collector
                • Parallel New + Serial GC
                • CMS (Concurrent Mark and Sweep)
                • G1 (Garbage First, available in Java7)

                Regarding JVM Specification:

                • JVM specification does not specify any particular garbage collection technique, the decision to choose the garbage collection algorithm is left to the discretion of the implementors as they better know the constraints of the target device.
                • JVM specification mentions the need of garbage collection on heap, it leaves garbage collection or compacting the method area on implementers.
                • A garbage collector is not strictly required but heap memory should be managed.
                • The Java language specification states that a finalizer code will be executed only once. Finalizer are allowed to "resurrect" the object again, that is it'll be referenced again, but finalizer will not run next time.

                Additional Responsibilities:

                • Heap Defragmentation

                Disadvantages:

                • Developer has no control on Garbage Collection, reducing the use the finalizers.
                • At times, it may lead to uneven performance of the application components, as we don't know when Garbage collection will run and how much resources and time it'll consume.

                Steps:

                • Garbage Detection
                  • Identification of live and garbage objects.
                  • Objects on heap which don't have any active references are available for garbage collection.
                  • This process is also called Marking.
                • Reclaim Memory
                  • Removes unreferenced objects leaving referenced objects and pointers to free space.
                • Optional Step: Compacting
                  • Defragments the memory space, compacts the remaining referenced objects. This makes new memory allocation much easier and faster.

                Stop the World Pauses:

                • Stop-the-world is term for JVM stopping the application (all threads) from running to execute a GC.
                • The interrupted tasks will resume only after the GC task has completed. 
                • GC tuning often means reducing this stop-the-world time.

                Disruptive Garbage Collection vs Deterministic Garbage Collection:

                • Garbage collection with noticable Stop the World pauses are called Disruptive Garbage collection.
                • Disadvantages - These are not suitable for Real-time systems. For end-users noticable pauses are irritating.
                • Solution Approach - Garbage collection should work incrementally, on small areas of heap at a time.
                  • If each incremental collection can be completed in < Threashhold time, then it is suitable for Real-time system.
                  • Example - Generational Collector used in Hotspot JVM, discussed below.

                Tracing Garbage Collector:

                • Tracing garbage collectors are the most common type of garbage collector. They first determine which objects are reachable (or potentially reachable), and then discard all remaining objects.

                Syntactic vs Semantic Garbage:

                •  The reachability definition of "garbage" is not optimal, as there are two cases.
                  • CASE #1: An object variable is now reassigned thus original object doesn't have any references left.
                  • CASE #2: An object is still available in the program, but it is not used anymore.
                • Syntactic Garbage (Objects that a program cannot possibly reach)
                  • It'll handle CASE #1 but not CASE #2.
                • Semantic Garbage (Objects that a program will never use again)
                  • It'll handle CASE #1 and CASE #2 both.

                Weak vs Strong References:

                • An object is eligible for garbage collection if there are no strong (i.e. ordinary) references to it, even though there still might be some weak references to it.
                • Weak Reference is usually reserved for a properly managed category of special reference objects which are safe to use even after the object disappears because they lapse to a safe value.
                • Weak References will be discussed in another post soon.

                Precise vs Conservative:

                • Collectors that correctly identify all references to an object are called precise (also exact or accurate) collectors.
                • Collectors that don't identify all references to an object correctly are called conservative or partly conservative collector.
                • Conservative garbage collectors have traditionally been used in conjunction with programming languages like C and C++, which were not originally designed with a garbage collector in mind.
                • Conservative collectors assume that any bit pattern in memory could be a pointer if, interpreted as a pointer, it would point into an allocated object.

                Moving (Compacting) vs Non-Moving (Non-compacting) Garbage Collectors

                • A moving GC strategy appears costly and low performance but it gives better performance. Following are details on this:
                  • Since memory is defragmented, large contigous memory is available, new objects can be allocated very quickly.
                  • No additional work is required to reclaim the space freed by dead objects; the entire region of memory from which reachable objects were moved can be considered free space.
                  • While moving the objects special care is needed for objects passed to native methods, as there might be native pointers pointing to this.
                • Updating references after moving objects is made simpler by adding another layer of abstraction in between. Object references will point to a table of object handles and not directly refer to objects. Thus after de-fragmentation, only the object handle table will get updated.

                Garbage Detection:

                • An object becomes eligible for garbage collection if its all references are null, i.e. If its not reachable from any live threads or any static references.
                • Achieved by defining a set of roots and determining reachability from the roots.
                • A distinguished set of objects are assumed to be reachable: these are known as the roots.
                • Typically, set of roots include all the objects referenced from anywhere in the call stack, and any global variables.
                  • Object references in Local variables and 
                  • Operand stack frame, 
                  • Static members of classes in method area, 
                  • Object references passed to currently executing native methods, etc.
                • An object is reachable if there is some path of references from the roots by which the executing program can access the object. Reachability is a transitive closure.
                • The roots are always accessible to the program. Any objects that are reachable from the roots are considered live. 
                • Objects that are not reachable are considered garbage.
                • Cyclic dependencies are also taken care this way.

                Approaches for Garbage Detection:

                • Tracing
                  • Trace the references from roots.
                  • Mark and Swipe is basic Tracing Collector.
                • Reference Counting
                  • Keeps count of the references to an object.
                  • Advantage - It can run in small chunks of time closely interwoven with the execution of the program. This characteristic makes it particularly suitable for real-time environments where the program can't be interrupted for very long.
                  • Disadvantage - It does not detect cycles: two or more objects that refer to one another.
                  • This technique is currently out of favor.

                Approaches for Heap Fragmentation Problem:

                • Compacting Collector
                  • Slide/Move live objects to defragment the heap area.
                  • Examples:
                    • Mark and Swipe
                    • Tri-color Marking
                • Copying Collector
                  • Copying garbage collectors move all live objects to a new area.
                  • Examples:
                    • Stop-and-Copy

                Generational Garbage Collection

                • The generational collection technique can be applied to mark and sweep algorithms as well as copying algorithms.
                • Dividing the heap into generations of objects can help improve the efficiency of the basic underlying garbage collection algorithm.
                • The most recently created objects are most likely to become unreachable quickly (known as infant mortality or the generational hypothesis).
                • Heap is divided into two or more sub-heaps, each of which serves one "generation" of objects.
                • The younger generation is garbage collected more frequently than older generation. 
                • Once an object has survived a few garbage collections as a member of the youngest generation, the object is promoted to the next generation: it is moved to another sub-heap.
                • Every sub-heap except the mature sub-heap can be given a maximum size.
                • Any objects that don't fit in the sub-heaps of the younger generations must go into the mature object space, thus mature object space cannot be given a maximum size.
                • It ensures that most incremental GC will be complete in less than a threshhold time. Only exception is Mature Generation.
                • Following image shows generational garbage collection in Hotspot JVM:

                Train Algorithm:

                • Specifies an organization for the mature object space of a generational collector for time bound incremental collections of the mature object space.
                • The train algorithm, which was first proposed by Richard Hudson and Eliot Moss and is currently used by Sun's Hotspot virtual machine.
                • Divides the mature object space into fixed-sized blocks of memory, each of which is collected individually during a separate invocation of the algorithm.
                  • Each block belongs to one set
                  • The blocks within a set are ordered, and the sets themselves are ordered. 
                • Small number indicate an older block within a set and Set with the heap.
                • For more details on this alogorithm, please google or refer to references section at the end of the Blog post.


                Types of Garbage Collectors (Garbage Collection Approaches/Strategies/Algorithms)

                • Stop-and-Copy (Semi-space) Collector
                  • Memory is partitioned into a "from space" and "to space". 
                  • Initially, objects are allocated into "to space" until they become full and a collection is triggered. 
                  • At the start of a collection, the "to space" becomes the "from space", and vice versa. 
                  • The objects reachable from the root set are copied from the "from space" to the "to space". 
                • Mark and Sweep
                  • This is an example of tracing collector.
                  • Each object in memory has a flag (typically a single bit) reserved for garbage collection use only.
                  • In Garbage detection, every object that is ultimately pointed to from the root set is marked.
                  • In Memory Reclaim step, entire memory is scanned, all non-reachable objects are freed.
                  • Disadvantage - Entire system must be suspended during garbage collection; no mutation of the working set can be allowed. This will cause programs to 'freeze' periodically (and generally unpredictab'ly), making real-time and time-critical applications impossible.
                • Tri-Color Marking:
                  • This is an example of tracing collector.
                  • White-Set (Condemned Set)
                    • Objects that are candidates for having their memory recycled.
                  • Black-Set
                    • Objects that can cheaply be proven to have no references to objects in the white set, but are also not chosen to be candidates for recycling; in many implementations, the black set starts off empty.
                    • In many implementations, the black set starts off empty.
                  •  Grey-Set
                    • Objects that are reachable from root references but the objects referenced by grey objects haven't been scanned yet. 
                    • The grey state means we still need to check any objects that the object references.
                    • Grey objects will eventually end up in the black set.
                  •  The grey set is initialised to objects which are referenced directly at root level; typically all other objects are initially placed in the white set.
                  • Objects can move from white to grey to black, never in the other direction.
                  • Advantage: it can be performed 'on-the-fly'.
                • Mark and Don't sweep
                  • This is an example of tracing collector.
                  • All reachable objects are always black.
                  • A white object is unused memory and may be allocated.
                  • The interpretation of the black/white bit can change. Initially, the black/white bit may have the sense of (0=white, 1=black).
                  • If an allocation operation ever fails to find any available memory, the sense of the black/white bit is then inverted (0=black, 1=white). Thus all objects become white. A marking phase begins immediatly to mark reachable objects black.

                Adaptive Collectors

                • An adaptive algorithm monitors the current situation on the heap and adjusts its garbage collection algorithm and configuration.

                Oracle Java 7 G1 (Garbage First) Garbage Collector:

                • Compact free space without lengthy and more predictable GC induced pause times.
                • Its still not suitable for Real-Time systems.
                • Targetted for multi-processors with large memories.
                • G1 is both concurrent and parallel. 
                  • It uses all available CPUs to speed up its “stop-the-world” pauses. 
                  • It also works concurrently with running Java threads to minimize whole-heap operations during stop-the-world pauses.

                Monday, November 4, 2013

                Java Virtual Machine - Introduction

                Typical Java Environment consists of following:
                •  Java Programming Language
                  • JDK
                  • Source code is in Java.
                • Java Class File Format
                  • Bytecode
                • Java API
                  • Standard classes and interfaces of JDK.
                • JVM
                  • Java Virtual Machine

                JVM:

                • The Java Virtual Machine, or JVM, is code executing component of Java platform.
                • Abstract machine that runs compiled Java programs.
                • The JVM is "virtual" because it is implemented in software on top of a "real" hardware platform and operating system.
                • The Java Virtual Machine is an abstract computing machine. Like a real computing machine, it has an instruction set and manipulates various memory areas at run time. 
                • Oracle JVM specifications specifies an abstract machine, it doesn't describe any particular implementation of JVM.
                • Java is for platform-independence, each Java platform has different constraints. Java specification doesn’t give hard and fast rules about the design of JVM with respect to memory and other aspects. JVM is implemented specifically for each platform, and implementation of JVM is left to jvm implementers.

                Role:

                • Read the Class file format (Bytecode) and correctly performs the operations specified in it.

                Key points:

                • Any implementation details like memory structures, garbage-collection etc are not part of the Java Virtual Machine's specification would unnecessarily constrain the creativity of implementers.
                • The Java Virtual Machine knows nothing of the Java programming language, it only cares for Virtual Machine instructions (or bytecodes).
                • All Java Virtual Machine implementations must recognize the Java class file format, but individual implementations may also recognize other binary formats.
                • Any language with functionality that can be expressed in terms of a valid class file can be hosted by the Java Virtual Machine.
                • For the sake of security, the Java Virtual Machine imposes strong syntactic and structural constraints on the code in a class file for security concerns.

                Advantages:  

                • Hardware and operating system independence. 
                • Small size of its compiled code. 
                • Protect users from malicious programs. 
                  • Bytecode is carefully inspected by JVM before execution.

                JVM Implementation:

                • Like most virtual machines, the Java virtual machine machine has a stack-based architecture akin to a microcontroller/microprocessor. 
                • JVM doesn't have registers for storing arbitrary values. All computation in the JVM centers on the stack, everything must be pushed onto the stack before it can be used in a calculation.
                • JVM are usually coded for a particular OS but it can also be coded directly on hardware.
                • JVM also has low level support for Java like classes and methods, which amounts to a highly idiosyncratic memory model and capability-based architecture.
                • JVM has no built-in support for dynamically typed languages.
                • JVM supports following 7 primitive types:
                  • byte     -    one-byte signed two's complement integer
                  • short    -    two-byte signed two's complement integer
                  • int        -    4-byte signed two's complement integer
                  • long     -    8-b yte signed two's complement integer
                  • float     -    4-byte IEEE 754 single-precision float
                  • double -    8-byte IEEE 754 double-precision float
                  • char     -    2-byte unsigned Unicode character
                • Few Examples:
                  • Most popular JVM implementation is from Oracle and is named HotSpot, written in C++.
                  • Jinitiator is another popular JVM implementation, especially in Oracle Apps community, developed by Oracle for supporting forms on websites before they purchased Sun. 
                  • Mac OS Runtime for Java (MRJ, originally Macintosh Runtime for Java).
                  • SAPJVM (SAP) is a licensed and modified SUN JVM ported to all supported platforms of SAP NetWeaver

                About Bytecode

                • Machine language of the Java virtual machine.
                • Each instruction consists of a one-byte opcode(represents operation) followed by zero or more operands.
                • An opcode may optionally be followed by operands(represents parameters required by opcodes).
                • The total number of opcodes is less (~200), each opcodes requires only one byte. 
                  • This helps in minimizing the size of class files and JVM implementation.
                • Java Bytecode is an intermediate language which is typically compiled from Java but it can also be compiled from other programming language, ex ADA.
                • Class files contain bytecode and a symbol table, as well as other ancillary information.
                • Any language with functionality that can be expressed in terms of a valid class file can be hosted by the Java Virtual Machine.
                • JVM has instructions for Load/Store of variables, Arithmetic, Type Conversions, Stack Management, Exception management, and Monitor based concurrency control etc.
                • Examples of Opcodes:
                  • iload, lload, fload, and dload  are used to load int, long, float and double operand on the stack respectively.
                  • istore, fstore are used to pop int and float from the stack to a variable.
                  • aload, astore operates on references.
                • There is no support for loops and binary logical operators (|| &&). These are implemented by compiler with jump instructions.

                Class File

                • Each class file contains the definition of a single class or interface. 
                • A class file consists of a stream of 8-bit bytes. All 16-bit, 32-bit, and 64-bit quantities are constructed by reading in two, four, and eight consecutive 8-bit bytes, respectively. 
                • Multibyte data items are always stored in big-endian.

                Execution Engine:

                • It consists of following:
                  • Bytecode Interpreter
                  • JIT (Just In Time) Compiler
                    • Since byte code is interpreted it executes slower than compiled machine code.
                    • Just-in-time compilation (JIT) is also known as dynamic translation.
                    • JIT is used to improve the runtime performance of byte code.
                    • The program is stored in memory as byte code, but the code segment currently running is preparatively compiled to physical machine code in order to run faster.
                  • Virtual Processor

                JRE:

                • Java Execution Environment (Java Runtime Environment). 
                • JRE contained JVM and java class libraries that implement java API.

                Other JVM Languages

                • Groovy
                • Scala
                • Jython
                • JRuby
                • Kotlin