Saturday, December 21, 2019

DevOps



Continuous Development
Developers uses tools to develop the code. Developed code get pushed to source code management. - Visual Studio, Eclipse, Intellij
devops engineers are responsible to maintain the code using "source code management tools" - git, bitbucket, mercurial, svn
Continuous Integration - jenkins, bamboo, circleci, teamcity
Unit Testing - junit, testng
Code build - maven, ant, gradle
Code Analysis - SonarQube
Code Artifacts - Nexus
Continuous Deployment - Ansible, jenkins, puppet, AWS code deploy
Infrastructure - docker, kubernetes, AWS, Azure
Configuration Management - Ansible
Continuous Testing - selenium
Continuous Monitoring - Nagios

Sunday, December 15, 2019

ReactJS library - develop modern web apps

Based on MVC architecture, React JS library provides developers with the ability to create dynamic web page templates (e.g., pages with an extensive amount of interactive elements on them).

ReactJS is not a framework. ReactJS describes itself as the V in the MVC (Model-View-Controller) design pattern. It's a view library that you can combine with frameworks such as AngularJS, Ember, and Meteor or even in conjunction with other popular JavaScript libraries, such as Knockout.

Many people use React on its own and combine it with a data flow pattern called Flux. The idea behind Flux is to establish unidirectional data flow, meaning that data should originate at a single point in your app and flow downwards.

Installation
1) install Node.js, npm
2) After that, install create-react-app package as below:-
$ npm install -g create-react-app

It is possible to manually create a React app, but Facebook has created a node module create-react-app to generate a boilerplate version of a React application.


Now create a New Single-Page React App by using create-react-app Package
$ npx create-react-app webshop

commands to run :-
npm start - starts the development server
npm run build - bundles the app into static files for production
npm test - starts the test runner
npm run eject - removes this tool and copies build dependencies, configuration files and scripts into app directory.

Understanding the Project Structure



/src/index.js

import React from "react";
import ReactDOM from "react-dom";

//JSX
ReactDOM.render(<h1>Hello World</h1>, document.getElementById("root"));

We are telling React what do we want to render (first argument), and where do we want this to be rendered (second argument).

Let's start with the first one.
Probably you wonder why are you putting an HTML element in the middle of your JavaScript parameter?
Fortunately, React creators created a language called JSX.  JSX (JavaScript XML) is an extension to the JavaScript language syntax. It is very much like a JavaScript rendition or version of HTML, in fact we're going to see that most of JSX looks almost identical to HTML with those few slight differences.

So this is a reason why do we have to import React in the first line.  The React library is the one that will enable JSX to work the way it's supposed to work.

In fact if  you remove or comment out the import React line and try to save it and refresh the browser, it tells me that React is not defined even though we're not explicitly using React anywhere in my code.

public/index.html


<div id="root"></div>

Although the initial div is empty, ReactDOM.render() is actually attaching React code to the container dynamically. Obviously, we do not have to attach it to root. We can attach it to any other valid DOM element:

<div id="static">Static Content1</div><div id="root"></div><div id="static">Static Content2</div>

React.Fragment
You cannot render two JSX objects next to each other. It will cause an error. But instead they have to be wrapped in something so that they count as just one element with two elements inside for example

ReactDOM.render(<h1>Hello World</h1><h2>Sub heading</h2>, document.getElementById("root"));

ReactDOM.render(
    <div>
      <h1>Hello World</h1>
      <h2>Sub heading</h2>
    </div>,
    document.getElementById("root")
  );

If you don't want to wrap it with an extra div, there is a way to do that as well. Instead of div, simply use the special container - <React.Fragment>.

  ReactDOM.render(
    <React.Fragment>
      <h1>Hello World</h1>
      <h2>Sub heading</h2>
    </React.Fragment>,
    document.getElementById("root")
  );

App class
This is the definition of main class. For now, think of a class as of definition of the component.

class App extends Component {
    constructor(props) { ... }
        render() {
        return (..);
        }
    }

Whenever React renders (is mounting) some class (components) it executes a few functions in a certain order. For now, just remember that constructor() is called before the render() function.

Mounting phase
These methods are called in the following order when an instance of a component is being created and inserted into the DOM:

constructor()
getDerivedStateFromProps()
render()
componentDidMount()

functions() — after calling the constructor we have a few functions that are used within the application.
render() — this function you already know. It contains JSX code that will be rendered to the browser.

Creating a Web Shop

React focuses on a core set of the features that are required by web applications :-
core react libraries - react, react-dom, react-scripts

React relies on supporting packages to create complete applications :-
bootstrap - This package provides the CSS styles that is used to present HTML content.
fontawesome-free - This package provides icons that can be included in HTML content.
redux - This package provides a data store, which simplifies the process of coordinating the different parts of the application.
react-redux - This package integrates a Redux data store into a React application.
react-router-dom  - This package provides URL routing, which allows the content presented to the user to be selected based on the browser’s current URL.
axios - This package is used to make HTTP requests and will be used to access RESTful and
GraphQL services.
graphql - This package contains the reference implementation of the GraphQL specification.
apollo-boost - This package contains a client used to consume a GraphQL service.
react-apollo - This package is used to integrate the GraphQL client into a React application.





When creating any kind of website, it's often beneficial to create a mock-up of how you want the page to look before proceeding to write any code.  This makes it easier to visualize how you want your site to look and what components you need to create.

You can use any kind of mock-up tool to create this, even a sheet of paper will do.

Looking at our website mock-up, we can see that we need to create the following components:
• A layout component
• A home page component for the front page
• A menu component with a brand name and the most important links
• A company information component
• A product list component
• An item component
• A checkout component
• A receipt component

These are just the view components.

In addition to these, we'll need to create data stores and actions and sub-components for the main ones.

Creating the layout
First of all, we need a basic layout for our webshop. There are many options available for you.
For instance, you can choose any one of the many open source CSS frameworks, such as Bootstrap or Foundation, or you can strike your own path and build up a basic grid and bring in elements as you see fit.

For simplicity's sake, we'll be going with Bootstrap for this webshop. It's a hugely popular framework that is easy to work with and has excellent support for React.

Add a few more packages -
react-bootstrap, react-router, lodash, reflux, superagent and react-router-bootstrap.
npm install --save <package>

This will put these packages in regular dependencies section in package.json

In order for the smart phones to show the page in proper scale, we need to add this meta tag as well:

<meta name="viewport" content="width=device-width, initialscale=1">

This notifies the smart phone browser that you want to display the page in full width with a scale of 1. You can play with the scale and width, but in most cases, this setting is what you want.


Adding your own CSS code
We already have a CSS file in the src folder. We're going to use a very basic CSS layout and rely on Bootstrap for the most part. Edit src/app.css and replace it with the following code:

body {
  background:#eee;
  padding:62px 0 0 0;
 }
 .row {
  padding:0 0 20px 0;
 }
 .summary {
  border-bottom: 3px double black;
 }

The padding is there simply to make sure that the content falls inside the menu.

Adding a route handler
Create a file called router.jsx and also a new file called layout.jsx, which will be our primary route handler.  This is where the contents of your route changes will go. Everything you put around it will not be changed when you switch to a new route, so this is where you place static elements, such as headers, footers, and asides.

The menu and footer
It's time to start working on the visible menu components. Let's begin with the menu and the footer. Looking at our mock-up, we see that we want to build a full-width section with the brand name of the shop and the menu links, and at the bottom, we want a single centered line of text with a copyright notice.

We'll do this by adding the following import to our import section in the layout.jsx file:
import Menu from "./components/menu.jsx";

import Footer from "./components/footer";



Let's scan the JSX code. Our app is split into two columns using Bootstrap grid (Container, Rows, and Columns) thanks to that columns will either be displayed next to each other (large screen) or one below the other.


Thursday, August 1, 2019

AOP extends OOP

OOP is mainly used to organise your business logic while AOP helps to organise your non-functional things like Auditing, Logging, Transaction Management , Performance Tracking, Security etc

This way you can decouple your business logic with non-fictional logic that makes code cleaner.

OOP and AOP are not mutually exclusive. AOP can be good addition to OOP.


AOP provides a nice way to implement cross-cutting concerns like logging, performance tracking, security over different classes in your application without having to change the classes themselves.
 
These cross-cutting concerns are pieces of logic that have to be applied at many places but actually don't have anything to do with the business logic.

You shouldn't see AOP as a replacement of OOP, more as an nice add-on, that makes your code more clean, loosely-coupled and focused on the business logic. So by applying AOP you will get 2 major benefits:

1. The logic for each concern is now in one place, as opposed to being scattered all over the code base.

2. classes are cleaner since they only contain code for their primary concern (or core functionality) and secondary concerns have been moved to aspects.

This is a way of doing runtime-weaving.

Example;-

1. Assume you have a graphical class with many "set()" methods.
2. After each set() method, the data of the graphics changed, thus the graphics changed and thus the graphics need to be updated on screen.
3. Assume to repaint the graphics you must call "Display.update()".

The classical approach is to solve this by adding more code. At the end of each set method you write

void set(...) {
    :
    :
    Display.update();
}

If you have 3 set-methods, that is not a problem. If you have 200 (hypothetical), it's getting real painful to add this everywhere.

Also whenever you add a new set-method, you must be sure to not forget adding this to the end, otherwise you just created a bug.

AOP solves this without adding tons of code, instead you add an aspect:

after() : set() {
   Display.update();
}


And that's it! Instead of writing the update code yourself, you just tell the system that after a set() pointcut has been reached, it must run this code and it will run this code.


No need to update 200 methods, no need to make sure you don't forget to add this code on a new set-method. Additionally you just need a pointcut:

pointcut set() : execution(* set*(*) ) && this(MyGraphicsClass) && within(com.company.*);

What does that mean? That means if a method is named "set*" (* means any name might follow after set), regardless of what the method returns (first asterisk) or what parameters it takes (third asterisk) and it is a method of MyGraphicsClass and this class is part of the package "com.company.*", then this is a set() pointcut. And our first code says "after running any method that is a set pointcut, run the following code".

See how AOP elegantly solves the problem here? Actually everything described here can be done at compile time. A AOP preprocessor can just modify your source (e.g. adding Display.update() to the end of every set-pointcut method) before even compiling the class itself.



Optimize Queries for Speed and Performance

Tip #1: Index All Columns Used in 'where', 'order by', and 'group by' Clauses

Though indexes may take up more space and decrease performance on inserts, deletes, and updates.
However, indexes can considerably reduce select query execution time.

without index => full table scan

mysql> select customer_name from customers where customer_id='140385';
The above query will force Database server to conduct a full table scan (start to finish) to retrieve the record that we are searching.
Database server has a special 'EXPLAIN' statement that you can use alongside select, delete, insert, replace and update statements to analyze your queries.

Once you append the query before an SQL statement,
mysql> explain select customer_id, customer_name from customers where customer_id='140385';
Server displays information from the optimizer about the intended execution plan.

+----+-------------+-----------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table     | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+-----------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | customers | NULL       | ALL  | NULL          | NULL | NULL    | NULL |  500 |    10.00 | Using where |
+----+-------------+-----------+------------+------+---------------+------+---------+------+------+----------+-------------+

As you can see, the optimizer has displayed very important information that can help us to fine-tune our database table.
First, it is clear that MySQL will conduct a full table scan because key column is 'NULL'.
Second, MySQL server has clearly indicated that it's going to conduct a full scan on the 500 rows in our database.
To optimize the above query, we can just add an index to the 'customer_id' field.

If we run the explain statement one more time, we will get the below results:

mysql> Explain select customer_id, customer_name from customers where customer_id='140385';
+----+-------------+-----------+------------+------+---------------+-------------+---------+-------+------+----------+-------+
| id | select_type | table     | partitions | type | possible_keys | key         | key_len | ref   | rows | filtered | Extra |
+----+-------------+-----------+------------+------+---------------+-------------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | customers | NULL       | ref  | customer_id   | customer_id | 13      | const |    1 |   100.00 | NULL  |
+----+-------------+-----------+------------+------+---------------+-------------+---------+-------+------+----------+-------+

From the above explain output, it's clear that MySQL server will use our index (customer_Id) to search the table.
You can clearly see that the number of rows to scan will be 1. Although I run the above query in a table with 500 records, indexes can be very useful when you are querying a large dataset (e.g. a table with 1 million rows).


Tip 2: Optimize Like Statements With Union Clause

Sometimes, you may want to run queries using the comparison operator 'or' on different fields or columns in a particular table. When the 'or' keyword is used too much in where clause, it might make the MySQL optimizer to incorrectly choose a full table scan to retrieve a record.

A union clause can make the query run faster especially if you have an index that can optimize one side of the query and a different index to optimize the other side.

Example, consider a case where you are running the below query with the 'first_name' and 'last_name' indexed:

mysql> select * from students where first_name like  'Ade%'  OR last_name like 'Ade%' ;
The query above can run far much slower compared to the below query which uses a union operator merge the results of 2 separate fast queries that takes advantage of the indexes.

mysql> select  from students where first_name like  'Ade%'  UNION ALL select  from students where last_name like 'Ade%' ;

Tip 3: Avoid Like Expressions With Leading Wildcards

MySQL is not able to utilize indexes when there is a leading wildcard in a query. If we take our example above on the students table, a search like this will cause MySQL to perform full table scan even if you have indexed the 'first_name' field on the students table.

mysql> select * from students where first_name like  '%Ade'  ;

We can prove this using the explain keyword:

mysql> explain select * from students where first_name like  '%Ade'  ;
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table    | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | students | NULL       | ALL  | NULL          | NULL | NULL    | NULL |  500 |    11.11 | Using where |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
As you can see above, MySQL is going to scan all the 500 rows in our students table and make will make the query extremely slow.

Tip 4: Take Advantage of MySQL Full-Text Searches

If you are faced with a situation where you need to search data using wildcards and you don't want your database to underperform, you should consider using MySQL full-text search (FTS) because it is far much faster than queries using wildcard characters.

Furthermore, FTS can also bring better and relevant results when you are searching a huge database.

To add a full-text search index to the students sample table, we can use the below MySQL command:

mysql>Alter table students ADD FULLTEXT (first_name, last_name);
mysql>Select * from students where match(first_name, last_name) AGAINST ('Ade');
In the above example, we have specified the columns that we want to be matched (first_name and last_name) against our search keyword ('Ade').

If we query the optimizer about the execution plan of the above query, we will get the following results:

mysql> explain Select * from students where match(first_name, last_name) AGAINST ('Ade');
+----+-------------+----------+------------+----------+---------------+------------+---------+-------+------+----------+-------------------------------+
| id | select_type | table    | partitions | type     | possible_keys | key        | key_len | ref   | rows | filtered | Extra                         |
+----+-------------+----------+------------+----------+---------------+------------+---------+-------+------+----------+-------------------------------+
|  1 | SIMPLE      | students | NULL       | fulltext | first_name    | first_name | 0       | const |    1 |   100.00 | Using where; Ft_hints: sorted |
+----+-------------+----------+------------+----------+---------------+------------+---------+-------+------+----------+-------------------------------+
It's clear that only a single row will be scanned even if our student's database has 500 rows and this will speed up the database.


LIKE vs CONTAINS on SQL Server

Which one of the following queries is faster (LIKE vs CONTAINS)?

SELECT * FROM table WHERE Column LIKE '%test%';
or
SELECT * FROM table WHERE Contains(Column, "test");


The second should be faster, because it can use some form of index (in this case, a full text index).
Of course, this form of query is only available if the column is in a full text index. If it isn't, then only the first form is available.

The first query, using LIKE, will be unable to use an index, since it starts with a wildcard, so will always require a full table scan.

***********************************************************************

Optimize Your Database Schema
Even if you optimize your MySQL queries and fail to come up with a good database structure, your database performance can still halt when your data increases.

Normalize Tables
First, normalize all database tables even if it will involve some trade-offs. For instance, if you are creating two tables to hold customers data and orders, you should reference the customer on the orders table using the customer id as opposed to repeating the customer's name on the orders table. The latter will cause your database to bloat.

The image below refers to a database schema that is designed for performance without any data redundancy. In MySQL database normalization, you should represent a fact only once in the entire database. Don't repeat the customer name in every table; instead just use the customer_Id for reference in other tables.

Image title

Also, always use the same data type for storing similar values even if they are on different tables, for instance, the schema above uses 'INT' data type to store 'customer_id' both in the customers and orders table.

Use Optimal Data Types
MySQL supports different data types including integer, float, double, date, date_time, Varchar, and text, among others. When designing your tables, you should know that "shorter is always better."

For instances, if you are designing a system user's table which will hold less than 100 users, you should use 'TINYINT' data type for the 'user_id' field because it will accommodate all your values from -128 to 128.

Also, if a field expects a date value (e.g. sales_order_date), using a date_time data type will be ideal because you don't have to run complicated functions to convert the field to date when retrieving records using SQL.

Use integer values if you expect all values to be numbers (e.g. in a student_id or a payment_id field). Remember, when it comes to computation, MySQL can do better with integer values as compared to text data types such as Varchar

Avoid Null Values
Null is the absence of any value in a column. You should avoid this kind of values whenever possible because they can harm your database results. For instance, if you want to get the sum of all orders in a database but a particular order record has a null amount, the expected result might misbehave unless you use MySQL 'ifnull' statement to return alternative value if a record is null.

In some cases, you might need to define a default value for a field if records don't have to include a mandatory value for that particular column/field.

Avoid Too Many Columns
Wide tables can be extremely expensive and require more CPU time to process. If possible, don't go above a hundred unless your business logic specifically calls for this.

Instead of creating one wide table, consider splitting it apart in to logical structures. For instance, if you are creating a customer table but you realize a customer can have multiple addresses, it is better to create a separate table for holding customers addresses that refer back to the customers table using the 'customer_id' field.

Optimize Joins
Always include fewer tables in your join statements. An SQL statement with poorly designed pattern that involves a lot of joins may not work well. A rule of thumb is to have utmost a dozen joins for each query.

MySQL Query Caching
If your website or application performs a lot of select queries (e.g. WordPress), you should take advantage of MySQL query caching feature. This will speed up performance when read operations are conducted.

The technology works by caching the select query alongside the resulting data set. This makes the query run faster since they are fetched from memory if they are executed more than once. However, if your application updates the table frequently, this will invalidate any cached query and result set.

You can check if your MySQL server has query cache enabled by running the command below:

mysql> show variables like 'have_query_cache';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| have_query_cache | YES   |
+------------------+-------+
1 row in <b>set</b> (0.00 sec)
Setting the MySQL Server Query Cache
You can set the MySQL query cache values by editing the configuration file ('/etc/mysql/my.cnf' or '/etc/mysql/mysql.conf.d/mysqld.cnf'). This will depend on your MySQL installation. Don't set a very large query cache size value because this will degrade the MySQL server due to cached overhead and locking. Values in the range of tens of megabytes are recommended.

To check the current value, use the command below:

mysql> show variables like 'query_cache_%' ;
+------------------------------+----------+
| Variable_name                | Value    |
+------------------------------+----------+
| query_cache_limit            | 1048576  |
| query_cache_min_res_unit     | 4096     |
| query_cache_size             | 16777216 |
| query_cache_type             | OFF      |
| query_cache_wlock_invalidate | OFF      |
+------------------------------+----------+
5 rows in <b>set</b> (0.00 sec)
Then to adjust the values, include the following on the MySQL configuration file:

query_cache_type=1
query_cache_size = 10M
query_cache_limit=256k
You can adjust the above values according to your server needs.

The directive 'query_cache_type=1' turns MySQL caching on if it was turned off by default.

The default 'query_cache_size' is 1MB and like we said above a value a range of around 10 MB is recommended. Also, the value must be over 40 KB otherwise MySQL server will throw a warning, "Query cache failed to set size".

The default 'query_cache_limit' is also 1MB. This value controls the amount of individual query result that can be can be cached.

Spring more popular than other java framework


Yes, we can build robust Java applications without using any framework. This is how it used to be earlier.
We can build our own framework using  java/servlets/jsp/html/css/javascript and jdbc to make applications.
But that requires huge development efforts includes implementing JEE patterns, offer abstractions, configure things or annotate the code to get the functionality we need , handling concerns like vendor portability, testability, deployabilty, incorporation of industry best practices, “packaging” / compatibility testing.. the list is endless.
So, for any commercial project development, all frameworks incorporates this endless list of things instead of you. When it comes to Java, there are many popular frameworks available and different programmers have different preferences. Some of those popular frameworks are Spring, Struts, Hibernate, JSF, Vaadin, GWT, Grails, and others.
Out of all these frameworks, Spring framework is the most popular and most widely used across the world. This can come as a surprise to many because Spring is one of the oldest frameworks in Java. The followings are the reason why Spring is more popular than other Java frameworks.

Spring is called the framework of frameworks -
The reason is that all the frameworks are supported by Spring such as Struts, Hibernate, JSF and likewise. Spring is a very powerful yet lightweight Java Enterprise Edition application development framework. There is no need for heavy Java EE application server. You can deploy its applications in any web container even in Tomcat. There are still some exclusive features that other frameworks cannot afford yet such as Spring Batch. It operates faster which is what we need in the current scenarios like mobile computing, cloud computing, and social computing. Its popularity has been sky high ever since its launch

Developer-Friendly -
The reason why most of the developers prefer Spring for almost any type and size of application developers is due to its friendly features. First of all, Spring is ready to get integrated with an existing system seamlessly and then you can work on it to improve it. In most of the enterprise level projects, the existing system of past projects can be improved to produce the rest of the present project. This saves time and resources in development, testing, and deployment. Spring offers this flexible to let any application developed in it to be integrated with third-party services or bring an application from third-party services to it so that the developers can build something new out of the old effortlessly.

Integration With Front-End Technology -
At the end of the project, the backend programming or framework has to gel well with the front-end for the project to run successfully. If you are using Spring for your back-end module development, you can rest assured that the integration with the front-end will be effortless. It supports all the leading front-end technology such as Struts, AngularJS, jQuery, JSF, JSP, Tiles and much more. You can switch between databases without writing too much of coding. There are literally unlimited plugins available that you can integrate with Spring and enhance your application to a whole different level. The flexibility that Spring offers is unmatched by any other Java framework. This unlimited sea of plugins is due to Spring having the largest community support of advanced and experienced developers than any other framework.

Aspect Oriented Programming –
Aspect oriented programming is a new concept that has been introduced by Spring and this has been a game changer for its popularity. There are many frameworks that are based on AOP but it is only Spring where it is perfectly implemented. This lets the developers develop applications in such a way that the business logic stays separated from the system services. As a matter of fact, Spring is tailor-made to develop applications that are complex in nature. It provides interfaces like Spring Core, Spring IoC, and Spring AOP so that different components can be developed individually and then integrated to achieve the perfect business logic.

MVC Framework –
Model-View-Controller framework is literally a darling in the application development industry. There is no better and simplified framework in Java other than Spring. MVC model helps in has development by modularity, easy unit testing and even easier deployment, maintenance, and troubleshooting. It is easier to test with JUnit framework. You can use Spring Container other than Enterprise container to develop applications and test the modules out with lesser effort. As a matter of fact, you can create business services with the need for Enterprise container which is highly beneficial for a development based company. There is no dearth of modules like Spring MVC, Spring ORM, Spring JDBC, and likewise. These varieties of modules are highly useful and boost the development rate to a great level. This also helps to divide a big project into modules and assign different teams to get them done in the due time.
Miscellaneous Features –
Another reason for its popularity over others can also be due to the fact that it has a simple learning curve in comparison to other frameworks which are slightly messy. This is the reason why companies are investing in teaching their new recruits about it in a shorter period of time and get the job done for future projects completely.


Wednesday, July 31, 2019

JMS | Java Message Service


JMS API is a Java message-oriented middleware API which contains a common set of interfaces to implement enterprise based messaging systems.

Benefit of using JMS are – loosely coupled application, reliability, and asynchronous communication between applications using JMS

ActiveMQ/ RabbitMQ is a popular message broker typically used for building integration between applications or different components of the same application using messages.

What is Message?
The message is a piece of information. It can be a text, XML document, JSON data or an Entity (Java Object) etc. The message is very useful data to communicate between different systems.

3 parts of message are:-

a)header :- It contains a number of  predefined fields using for proper delivery and routing.

b)body :- As the name suggests it is the body of messages. JMS API allows five types of message bodies.

        1.TextMessage :- Body contains String data

        2.ByteMessage :- Body contains byte data

        3. MapMessage :- Body contains data in key/value pair

        4.StreamMessage :-Body contains a stream of primitive  values

        5.ObjectMessage : – Body contains an object

        6.Message :- Nothing in body. Only header and properties.

c)properties :- Additional properties other than header.

JMS Architecture

JMS Architecture

How to Create a Simple JMS Queue in Weblogic Server 11g?

Create a JMS Server
Services > Messaging > JMS Servers
Select New -> 
Name: TestJMSServer
Persistent Store: (none)
Target: soa_server1 (or choose an available server)
Finish


The JMS server should now be visible in the list with Health OK.


Create a JMS Module


Services > Messaging > JMS Modules
Select New -> 
Name: TestJMSModule
Leave the other options empty
Target: soa_server1 (or choose an available server)
Leave “Would you like to add resources to this JMS system
module” unchecked
Finish

Create a JMS SubDeployment


Services > Messaging > JMS Modules
Select  -> TestJMSModule
Select the Subdeployments tab and New ->
Name: TestSubdeployment
Next
Here you can select the target(s) for the subdeployment. You can
choose either Servers (i.e. WebLogic managed servers, such as the
soa_server1) or JMS Servers such as the JMS Server created
earlier. As the purpose of our subdeployment in this example is to
target a specific JMS server, we will choose the JMS Server option.
Select theTestJMSServer created earlier

Finish

Create a Connection Factory

Create a JMS Queue



The JMS queue is now complete and can be accessed using the JNDI names

jms/TestConnectionFactory
jms/TestJMSQueue.

Send a Message to a JMS Queue?


import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

String url = "";

 public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";

 public final static String JMS_FACTORY="jms/TestConnectionFactory";

 public final static String QUEUE="jms/TestJMSQueue";

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, url);

InitialContext ic = new InitialContext(env);
QueueConnectionFactory  qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
QueueConnection qcon = qconFactory.createQueueConnection();
QueueSession qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = (Queue) ctx.lookup(QUEUE);

QueueSender qsender = qsession.createSender(queue);
TextMessage msg = qsession.createTextMessage();
msg.setText(message);

qcon.start();
qsender.send(msg);

qsender.close();
qsession.close();
qcon.close();


jms programming model


Receive a Message from a JMS Queue?

import javax.jms.*;  

public class MyListener implements MessageListener {  
  
    public void onMessage(Message m) {  
        try{  
        TextMessage msg=(TextMessage)m;  
      
        System.out.println("following message is received:"+msg.getText());  
        }catch(JMSException e){System.out.println(e);}  
    }  



createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
true -> transacted [commit(), rollback()]
false -> non -transacted

AUTO_ACKNOWLEDGE
CLIENT_ACKNOWLEDGE
DUPS_OK_ACKNOWLEDGE



JMS API supports the sending of any Serializable object as ObjectMessage object .

how an object is sent as a message between two client applications.
FirstClient.java creates an EventMessage object and sends it to the destination.
SecondClient.java is receiving the same EventMessage object from the same destination.



public class EventMessage implements Serializable {

private static final long serialVersionUID = 1L;

private int messageId;

private String messageText = "";

public EventMessage(int id, String messageText) {

this.messageId = id;

this.messageText = messageText;


}


producer = session.createProducer(destination);
EventMessage eventMessage = new EventMessage(1,"Message from FirstClient");
ObjectMessage objectMessage = session.createObjectMessage();
objectMessage.setObject(eventMessage);
producer.send(objectMessage);

consumer = session.createConsumer(destination);
Message message = consumer.receive();
if (message instanceof ObjectMessage) {
Object object = ((ObjectMessage) message).getObject();
System.out.println(this.getClass().getName()
+ "has received a message : " + (EventMessage) object);




TDD


Test-driven development (TDD)

is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards.

TDD is being quickly adopted by agile software developers for development of application source code and is even being adopted by Agile DBAs for database development.
  • Add a test
  • Run all tests and see if the new one fails
  • Write some code
  • Run tests
  • Refactor code
  • Repeat
Keep in mind that the idea behind TDD is to do the necessary minimum to make the tests pass and repeat the process until the whole functionality is implemented. At this moment we're only interested in making sure that "the method can take 0, 1 or 2 numbers". Run all the tests again and see them pass.

Benefits

Writing the tests first requires you to really consider what do you want from the code.
You receive fast feedback.
TDD creates a detailed specification.
TDD reduces time spent on rework.
You spend less time in the debugger.
You are able to identify the errors and problems quickly.


CI/CD Pipeline | modern DevOps process

CI/CD:- It bridges the gap between development and operations teams by automating the building, testing, and deployment of applications.

CI stands for Continuous Integration and CD stands for Continuous Delivery/Continuous Deployment. 

We can think of CI/CD as a process similar to a software development lifecycle.



The above pipeline is a logical demonstration of how software will move along the various stages in this lifecycle before it is delivered to the customer or before it is live in production.

web application ->
1. developers responsible for writing and committing code to version control system (git, svn)
2. developers build the web application [build/compilation phase]
3. after build phase, testing phase started [unit test]
4. when test completed, you move to deploy phase where you deploy it into a staging or a test server. Here, you can view the app in a simulator.
5. Once the code is deployed successfully, you can run another sanity test. If everything is accepted, then it can be deployed to production.

So the ultimate goal of CI/CD process is to automate this above entire process.

We will automate the pipeline in order to make the entire software development lifecycle in DevOps/automated mode. 


We can define entire job or the task.

From Git, Jenkins pulls the code and then Jenkins moves it into the commit phase, where the code is committed from every branch. The build phase is where we compile the code. If it is Java code, we use tools like maven in Jenkins and then compile that code, which can be deployed to run a series of tests. These test cases are overseen by Jenkins again.
Then, it moves on to the staging server to deploy it using Docker. After a series of unit tests or sanity tests, it moves on to production.




The CI/CD pipeline is one of the best practices for devops teams to implement, for delivering code changes more frequently and reliably.

Continuous Integration (CI) is a development practice that requires developers to implement small changes and check in code to version control system/ repositories frequently. Each check-in is then verified by an automated build, allowing teams to detect problems early. 

Continuous delivery(CDpicks up where continuous integration ends. CD automates the delivery of applications to selected infrastructure environments. Most teams work with multiple environments other than the production, such as development and testing environments, and CD ensures there is an automated way to push code changes to them.  CD automation then performs any necessary service calls to web servers, databases, and other services that may need to be restarted or follow other procedures when applications are deployed.

Benefits
there is significantly less back-tracking to discover where things went wrong, so you can spend more time building features.
Continuous Integration is cheap
Catch issues early and nip them in the bud
Spend less time debugging and more time adding features
Stop waiting to find out if your codes going to work
Reduce integration problems allowing you to deliver software more rapidly

Thursday, July 25, 2019

Method/Class level variable | Java Heap Space and Stack Memory

public class Memory {

public static void main(String[] args) { // Line 1
int i=1; // Line 2
Object obj = new Object(); // Line 3
Memory mem = new Memory(); // Line 4
mem.foo(obj); // Line 5
} // Line 9

private void foo(Object param) { // Line 6
String str = param.toString(); //// Line 7
System.out.println(str);
} // Line 8

}

As soon as we run the program, it loads all the Runtime classes into the Heap space. When main() method is found at line 1, Java Runtime creates stack memory to be used by main() method thread.
We are creating primitive local variable at line 2, so it’s created and stored in the stack memory of main() method.
Since we are creating an Object in line 3, it’s created in Heap memory and stack memory contains the reference for it. Similar process occurs when we create Memory object in line 4.
Now when we call foo() method in line 5, a block in the top of the stack is created to be used by foo() method. Since Java is pass by value, a new reference to Object is created in the foo() stack block in line 6.
A string is created in line 7, it goes in the String Pool in the heap space and a reference is created in the foo() stack space for it.
foo() method is terminated in line 8, at this time memory block allocated for foo() in stack becomes free.
In line 9, main() method terminates and the stack memory created for main() method is destroyed. Also the program ends at this line, hence Java Runtime frees all the memory and end the execution of the program.


Based on the above explanations, we can easily conclude following differences between Heap and Stack memory.

Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
Objects stored in the heap are globally accessible whereas stack memory can’t be accessed by other threads.
Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Young-Generation, Old-Generation etc, more details at Java Garbage Collection.
Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.
We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory. We can use -Xss to define the stack memory size.
When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error.
Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.


Local/method level-

place - declared inside method and block
scope - visible only in method and block
existence time - created when method is called and destroyed when method exits
default values - must be initialised before use otherwise it won’t compile
allocation - stack memory
don’t have to worry about concurrent access to local variables

Instance/class level-
place - declared inside class
scope - visible to all methods in class
existence time - Instance variables are created using new operator OR when class is loaded and destroyed by garbage collector when there is no reference to them.
default values - initialisation is not mandatory; if omitted then take default values 0,0.0,false,null
allocation - heap memory
have to worry about instance variables in a multi threaded env

_____________________________________________________________________




Web Development

Design Phase:- Below all these represent different stages of the UX/UI design flow:- Wireframes represent a very basic & visual repr...