Thursday, 23 November 2017

Rest Webservices

API types
  • Public, private, partner
  • No difference in implementation. 
  • Only difference in how it is managed
    • Security
    • Documentation
    • Access request
    • SLA management
API Key
  • An application programming interface key (API key) is a unique code that is passed in to an API to identify the calling application or user. ... The API key often acts as both a unique identifier and a secret token for authentication, and generally has a set of access that is specific to the identity associated with it.
Restful Design rules
  • Client Server-> both on different processes focusing on separation of concerns
  • uniform interface 
    • resources indentified by uri/url
    • Client receives representation of resource
    • self descriptive messages/metadata(http headers)
    • hypermedia
      • HATEOAS(hypermedia as the engine of application state)
  • stateless ->
  • caching -> use http headers
  • layered
  • code on demand(optional)
Statelessness
  • Challenges
    • increased chattiness 
  • Workaround is to leverage Cacheing
    • Caching can be implemented as DB, middle tier server, application/client, Gateway/proxy
  • Server should specify cache-control directives in responses to control Caching behavior
    • Cache-Control
      • No-Store -> no chaching
      • Private -> only on client device
      • Public -> cached any where
      • Max-age- Time in seconds for cache expiry
    • Caching helps in Scalability & performance
Layered Architecture
  • Each layer depends only on one layer
Code on Demand
  • Server can extend the functionality of client by sending code
REST API endpoint

API Security

  • Authentication
    • Basic
      • simple & easy
      • send credentials in HTTP header called Authorization
      • OK to use with HTTPS
      • Weakness
        • Credentials to be sent in every request
    • Tokens & JWT(Javascript web token)
      •  Invoke /token endpoint with credentials. Server will send Token
      • All subsequent calls can be made with just the Token inlieu of credentials.
    • API key & Secret
    • Oauth
  • Authorization
  • functional attack
 Token
  • It is encoded string used for authentication
  • JWT is common standard for creating Tokens and stands for Json webtoken.  
  • It has 3 parts - Header.Payload.Signature
    • Header
      • Type
      • Hashing algorithm
    • Payload 
      • Issuer
      • expiry
      • and many...
    • Signature
      • Created from base64 header+base64 payload
      • hashing above value with secret
API key & Secret
  • Key & secret given for application registered with Rest api owners
  • They are also called as clientId/Key & 
  • Secret is like password
  • usage
    • analytics
    •  tokens from api provider
    • Rate limiting

 
Webservices are services that are exposed to internet for programmatic access. They are online apis in java code.
REST Characteristics:
  • HTTP Exchange: Exchange of data happens over web ie http
  • Protocol: Message Format -> None(xml, json, text can be used as long as client and server understands)
  • Service definition: None. WADL is not popular are not widely used.
REST is a concept/idea. It doesn't have any specification. No committee to tell whats right or wrong.
REST is introduced by Roy Fielding in his doctoral thesis in 2000. It stands for REpresentational State Transfer. It is an architectural style. Roy is one of the authors of the HTTP specification.

Only guidelines and NO Rules.

'web services' are an 'integration' technology. Integration technologies are used when your software needs to exchange data with other systems.

It is a software system designed to support inter-operable machine-machine interaction over network.
  • Every Java standard has a Reference Implementation. 
  • Jersey is the RI for Jax-RS
  • Glass fish is Java EE RI and hence no additional downloads are required for REST.



REST - Representational State Transfer
Concepts:
















Sunday, 20 August 2017

Website Performance Aspects

Web Performance is all about making website overall experience faster.

  • How Browser works
    • Browser is single threaded 
      • Webpage is downloaded in Chunks. Everytime a Chunk is downloaded it does following operations
        • Interprets and creates DOM.
        • Layouting - Layout of various elements with their dimensions is constructed by browser.  This happens in memory.
        • Rendering - Displaying of webpage in pixels. 
      • Async Queue
        • This is responsible for Asyncronous requests
        • Ajax calls, set time intervals, set timeout
        • These are executed when browser has noting to do

  • Website speed test 
    • tools.pingdom.com
    • googles pagespeed
    • webpagetest.org 
  • Bandwidth Optimization - Website network optimization
    • Web Caching is very important for Bandwidth optimization. It is instructing browser to store files temporarily and use for a while. And not to download every time from internet. For more details refer to qnimate.com/all-about-web-caching
    •  CDN - Content delivery network makes the bandwidth of the website very very faster. 
    • Compression Resources decreases the size of resources. One can compress using checkgzipcompression.com. Browser uncompressess the compressed resources before using it.
    • External JS and Css files  mentioned in <head> of html are downloaded before proceeding with display of the page.  So always move js & css references to the end of the file (after </body> tag). 
    • Also, it is a good practice to combine multiple CSS into single Css. Same with js as well. This is to reduce Connection initialization to server which is expensive. This reduces bandwidth of the network connection.
    • Minifying resources
    • Use of Cookies. Cookies are used to store information on users computer. Use session cookies rather than regular cookies so that the information is stored on server and only ID is transferred between user and server.
  • Dealing with Images - How to make images load faster
    •  If website is not too much image oriented(nice to have only), decrease the quality of images. In this case the size decreases and so the network latency decreases. 
    • imageoptimizer.net
    • Image Sprite is collection of images into a single Image. A webpage with many images can take a long time to load and generates multiple server requests. Images sprite reduces number of server requests and saves bandwidth
    • Data URIs 
    • Responsive Images - Resize the image width according to the width of image container.
  • Render Optimization
    • Faster Animations 
  • Memory Optimization
    • Less memory consumption, less primary memory consumption. Everyone has limited amount of RAM.
 Multi Threading
  • HTML never supported multi threading. Programmers use setTimeout or setInterval to make the application behave like multithreaded applicaiton.  HTML5 provides builtin API to support multi threading.
  • HTML5 Web worker is a java script thread(or javascript file) that runs concurrently with the main thread. 
Global Variables
  • Do not create global variables. These are not destroyed by Garbage collector.
  • Declare variables within functions, so that, the object will be collected when the function scope is ended.
Animation
  • requestAnimationFrame - This is supported by modern browsers. Do not use setInterval and setTimeout. 
    • Timers callback rate is same even if browser is running in background state. But requestAnimationFrame slows down the rate when browser is in background state.
CSS3 Transitions and Animations vs Java script Animations
  • CSS3 is preferred as it can be understood by cpu directly. Javascript should be interpreted by browser and then by cpu
Preloading Resources using <link> element
  • We can ask browser to preload resource during safe time using <link> element with prefetch relation
    • <link rel="prefetch" href="qunimate.png">
    • These resources are fetched asynchronously during safe time by the browser
  •  Same can be acheived with Link: http response header
    • Link: <qnimate.png>; rel=prefetch
  • Same can be acheived with meta tag
    • <meta http-equiv="Link" content="<qnimate.png>; rel=prefetch">
Lazy loading
  • Load only when user is on that view port
    •  

Sunday, 4 June 2017

Java8 - New Features

Interface
  • We can provide implementation to existing/new interfaces by using "default" key word before the method definition
  • Support static methods
  •  
Streams
  • A sequence of elements supporting sequential and parallel aggregate operations.

New Date Time API
  • java.time is the package
  • LocalDate d = LocalDate.of(
    LocalTime t = LocalTime.now(ZoneId.of("Asia/Kuwait"));
    LocalDateTime
    ZoneId.getAvailableZoneIds()
    Instant.now()
Lambdas
  • Enables functional programming, Readable and concise code, Easier to use APIs and libraries, enables support for parallel processing

https://www.youtube.com/watch?v=tfbmYBcq5CM&index=20&list=PLqq-6Pq4lTTa9YGfyhyW2CqdtW9RtY-I3#t=2.097395

Programming Pradigms
  • Imperative programming: Programming with variables, lists, for-loops. eg: c
  • Functional programming: In unit of functions eg: excel
  • Object oriented programming: Classes & object eg: java, c#, c++
Java is definitively an Object-Oriented language, but recently it has added support for some functional programming features.

Benefits of Lambdas:
  • Enables Functional programming
  • Readable and concise code
  • Develop APIs and libraries that are easier to use
  • Support for parallel processing
Lambdas are just a functions in isolation(doesn't belog to class). Those functions can be treated as Values.

Examples:
public class TypeInferenceExample{
   public static void main(String[] args){
    printlambda(s->s.length());
    }
   public static void printlambda(StringLengthLambda l){
    System.out.print(l.getLength("hello lambda"));
    }
   interface StringLengthLambda{
    int getLength(String s);
  }
}

public class RunnableExample{
   public static void main(String[] args){
    Thread myThread = new Thread(new Runnable() {

    @Override
    public void run(){ System.out.println("inside runnable"); }
    });
    myThread.run();

    Thread myLambdaThread = new Thread(()->System.out.println("inside runnable"););
    myLambdaThread.run()
}

Functional Interface
    Interface that has only one abstact method is called a Functional interface. Such interfaces can be used for lambda types.

@FunctionalInterface annotation is used to mark the same.


Single Method interfaces are called "Functional Interfaces" or "Single Abstract Method" interfaces.
Lambda Expressions/Functional Expressions/Closures: Functional constructs in an Object Oriented Context-1

Lambda Functions
  • They are simply Anonymous Functions
  • An alternate to anonymous classes with a single method
  • Useful for quick and dirty bits of coding that don't need a class



Monday, 8 May 2017

Java Memory

Stack
  • There can be many stacks in JVM
  • Every thread has its own stack to store
    • Local variables(primitive and Object references)
    • method calls 
  • Data on STACK can only be seen by respective thread that owns it.
  • When the end of method is reached, stack variables are removed/popped out/destroyed.
Heap
  • One heap across ALL threads
  • All Objects are stored on HEAP(Class instances, Arrays,  Class Objects)
  • Allows us to store data that has longer life time than a single block or function.
    • eg: Objects that can be shared across methods
  • Value of primitive instance variable. 

Runtime Data Areas:

Method Area
  • Class level data/information
    • Meta infromation like
      • Names of type, superclass, super interfaces
      • Class or interface
      • type modifiers: abstract, final, public
    • Reference to class object
    • Field info
      • Name & type, 
      • Modifiers: static, final, access modifiers, transient, volatile
    • Filed type 
    • Value of primitive static variable. 
    • Runtime Constant pool
      • Literals
      • symbolic references
    • Method Info
      • Name
      • Return type
      • Number and type of arguments
      • Modifiers: static, final, access modifiers, abstract, synchronized, native
      • Method bytecode 
    • Method Table


NOTE: Prior to Java 8, method area was allocated in Permanent Generation(PermGen) space. It is completely removed in Java8. And method area has been moved to Native Heap. It is referred as Metaspace. Following are the reasons:
  • OutOfMemory is less likely as the metaspace has no max size for memory. System memory is limit. 
  • Improved GC process

Monday, 10 April 2017

Java Mission Control and Java Flight Recorder


https://www.youtube.com/watch?v=ULFZ_HuRjnI&list=PLKCk3OyNwIzsEVDq6zErLW7HSkY7aqdeT

https://www.youtube.com/watch?v=qrvDKp8iTIQ

https://www.youtube.com/watch?v=WMEpRUgp9Y4&list=PLSd9CXFWeMPR0nfizWQA1cms3W6iD2chw

https://www.youtube.com/watch?v=cY4LOmUymiY&list=PL7ie6G8tUCSPhCRBQMtHWlZ4fGFHCWxvs

java -Xmx32m -Xms16m -XX:+UnlockCommercialFeatures -XX:+FlightRecorder -XX:+UseSerialGC One

Records and analyses the jvm and the running applications.

Java Profiling is the process of monitoring various JVM level parameters such as Method Execution, Thread Execution, Object Creation and Garbage Collection. Java Profiling provides you with a finer view of your target application execution and its resource utilization.

Java Profiling may thus be summarized as measuring statistics of a Java application, specifically in terms of:
  • CPU time being utilized per method
  • Memory being utilized
  • Method call information
  • Objects being created
  • Objects being garbage collected
3 different kinds of Java profilers:
  1. Standard JVM Profilers that track every detail of the JVM (CPU, thread, memory, garbage collection, etc).
    1. Products like VisualVM, JProfiler, YourKit and Java Mission Control.
  2. Lightweight profilers that highlight your application with a bit of abstraction.
  3. Application Performance Management (APM) tools used for monitoring applications live in production environments.

 

Uses of Flight Recorder:
  • Method Profiling
  • Allocation Profiling
  • Latency Analysis
  • GC Analysis
  • I/O
  • Third Party Events

JMX- Java Management Extensions.
  • Dynamically monitor and manage jvm
  • Built into jvm
 Managed Beans
  • Objects manage JVM resources
  • MBeans stored in a server
JMX agents manage MBeans
JMX connectors connect to Agents

Java Flight Recorder
  • Recording and Analysis tool for Java JVMs
    • Records JVM events in the background
      • .jfr extension
      • binary file
      • self contained and self describing
    • Unobtrusive with minimal impact on performance
    • Creates detailed recording of jvm events
  • Recordings analyzed in Mission Control Console
    • Provides detailed information and analysis tools
    • Covers almost every aspect of JVM activity