Transaction management in JPA/Spring

Propagation is used to define how transactions related to each other. Common options

  • Required: Code will always run in a transaction. Create a new transaction or reuse one if available.
  • Requires_new: Code will always run in a new transaction. Suspend current transactions if one exists.


Isolation Defines the data contract between transactions.

  1. Read Uncommitted: Allows dirty reads
  2. Read Committed: Does not allow dirty reads
  3. Repeatable Read: If a row is read twice in the same transaction, the result will always be the same
  4. Serializable: Performs all transactions in a sequence


An isolation level is about how much a transaction may be impacted by the activities of other concurrent transactions. It supports consistency leaving the data across many tables in a consistent state. It involves locking rows and/or tables in a database.

The problem with multiple transactions
  • Scenario 1. If the T1 transaction reads data from table A1 that was written by another concurrent transaction T2. If on the way T2 is a rollback, the data obtained by T1 is an invalid one. E.g a=2 is original data. If T1 read a=1 that was written by T2.If T2 rollback then a=1 will be a rollback to a=2 in DB. But, Now, T1 has a=1 but in the DB table, it is changed to a=2.
  • Scenario2.If a T1 transaction reads data from table A1.If another concurrent transaction(T2) updates data on table A1. Then the data that T1 has read is different from table A1. Because T2 has updated the data in table A1.E.g if T1 read a=1 and T2 updated a=2.Then a!=b.
  • Scenario 3. If the T1 transaction reads data from table A1 with a certain number of rows. If another concurrent transaction(T2) inserts more rows on table A1. The number of rows read by T1 is different from the rows in table A1


Scenario 1 is called Dirty reads.
Scenario 2 is called Non-repeatable reads.
Scenario 3 is called Phantom reads.

So, the isolation level is the extent to which Scenario 1, Scenario 2, and Scenario 3 can be prevented. You can obtain a complete isolation level by implementing locking. That is preventing concurrent reads and writes to the same data from occurring. But it affects performance. The level of isolation depends upon application to application on how much isolation is required.


  1. ISOLATION_READ_UNCOMMITTED: Allows to read changes that haven’t yet been committed. It suffers from Scenario 1, Scenario 2, Scenario 3
  2. ISOLATION_READ_COMMITTED: Allows reads from concurrent transactions that have been committed. It may suffer from Scenario 2 and Scenario 3. Because other transactions may be updating the data.
  3. ISOLATION_REPEATABLE_READ: Multiple reads of the same field will yield the same results until it is changed by themselves.It may suffer from Scenario 3. Because other transactions maybe inserting the data
  4. ISOLATION_SERIALIZABLE: Scenario 1,Scenario 2,Scenario 3 never happens.It is complete isolation. It involves full locking. It affects performance because of locking.

Stack

What is stack?
--> Stack is the collection of objects accessed from one end.  eg. pile of the plate in the kitchen. It has two primitive operations are: Push for addition and Pop for deletion. All the operation are on the top of the stack.
--> LIFO: last in first out

PUSH Operation & Implementation:-
--> always added on top of the stack. syntax:- push(n)
eg.
-define the size of the stack.
- define the top of stack -1.
-push(n): it will push the element into the stack.

Overflow
-If there is no more space to push element in the stack, the stack is full!!!

POP Operation and Implementation:
-remove an element from the top of the stack. eg n = pop().

Underflow:
-if the stack has no more element and tried to remove the element. the stack is empty!!!

Advanced Multi Threading in Java [ Latch ] - Part 1

CountDown latch is one of the kinds of synchronizer which wait for another thread before performing the tasks or This is used to synchronize one or more tasks by enabling them to wait for the tasks completed by other tasks.  It was introduced in Java 5 along with other CyclicBarrier, Semaphore, CuncurrentHashMap and BlockingQueue. Its somehow like the wait and notify but in the more simpler form and will much less code.

It basically works in the latch principle. Or let us suppose we have a seller who is going to sell 10 (No. of operations) apples. The number of customers may be anything but what the seller is concerned about is the number of apples because when it reaches to 0 he can go home. The seller(Main Thread) will wait for the customers (awaits()). Let's say there are 10 customers(Threads) now who are in the line to buy Apple. When one customer buys that Apple then the number of apple decrease by 1 (countdown()) and another customer will get a chance to buy that apple so on the number of apples goes on decreases and finally become 0. After no apples left in the bucket, the seller can stop selling and go home happily. 

Note:: In CountDown Latch the countdown cannot be reset. 


Image result for CountDownLatch

Let's have a look at Java code::




#HappyCoding #CodingWorkspace

Display The Image On The Page

We're making our request to Unsplash, it's returning a response that we're then converting to JSON, and now we're seeing the actual JSON data. Fantastic! All we need to do now is display the image and caption on the page.

Here's the code that I'm using:


This code will be working following way
  • get the first image that's returned from Unsplash
  • create a <figure> tag with the small image
  • creates a <figcaption> that displays the text that was searched for along with the first name of the person that took the image
  • if no images were returned, it displays an error message to the us

#HappyCoding

jQuery methods used to make asynchronous calls

jQuery has a number of other methods that can be used to make asynchronous calls. These methods are:

Each one of these functions in turn calls jQuery's main .ajax() method. These are called "convenience methods" because they provide a convenient interface and do some default configuration of the request before calling .ajax().

Let's look at the .get() and .post() methods to see how they just call .ajax() under the hood.

Running an asynchronous request in the console. The request is for a resource on SWAPI. The request is displayed in the network pane.

So we can make a request with .ajax(), but we haven't handled the response yet.

#HappyCoding!!!

Zookeeper - Introduction

Image result for apache zookeeper


Introduction

Zookeeper is one of the famous apache's projects which is used to provide synchronized services across the servers i.e. it's a centralized infrastructure. It is very hard to manage and coordinate the different cluster at a time but zookeeper with its advanced API with the simple Architecture solves this issues. With the help of zookeeper, we can focus more on development rather than managing the clusters. 

Zookeeper does this by creating a file in its server known as znode, which resides in the memory of zookeeper. This node can be updated by any nodes in the clusters to update their status. This updated status can be gained by other nodes so that they can change their behaviors to provide the perfect services. 

Topics and partitions in Apache Kafka [Basic Topics]

Image result for apache Kafka

What are topics and partition in Kafka?
Topics are nothing but a particular stream of data. It is just like the table's in the database except without all the constraints. We can have as many topics as we want. Like in the database each topic is identified by its name. 
Similarly, topics are splits into partitions and each partition is ordered. Each message in the partition gets an incrementing id which is called offset.

Example::
Let us suppose we have a topic T which has a partition let P0 be one of them

step 1: Partition0 {initially it is empty}
step 2: Partition0 0 {here when we write a message to this then that message will have offset 0}
step 3: Partition0 0 1 {when we write another message to it then that message will have offset 1}
step 4: Partition0  0 1 2 and so on {just we described earlier in an incremental order}
and so on...

Note:: Offsets increase from 0 to n as we write data

Each partition will have their own offsets 

Partition0: 0 1 2 3 4 5 6 7  {here the partition goes from 0 to 7 }
Partition1: 0 1 2 3 4 5 {here the partiotion goes from 0 to 5}
Partition2: 0 1 2 3 4 5 6 7 8 {here the partition goes from 0 to 8}

so here the combination of these partitions[Partition0, Partition1, partition2] is called a TOPIC.

Things to keep in mind
  1. Offsets in one partition don't mean anything to other partition, Eg: offset 2 in Partition1 will be the same with offset 2 in other partitions.
  2. Orders are guaranteed only within the partitions. 
  3. Data in the partition are limited to the specific time. {default 2 weeks}
  4. Once the data is written in the partition it cannot be unchanged i.e. it is immutable.
  5. We push data to the topic, not the partitions.
  6. Unless we provide the key data is randomly assigned to the partitions.
  7. We can have as many partitions on the topic we want.
Happy Coding...

GO - Basic Variable declaration - Part 3

Image result for golang
Defining variables in the go
we use var to define a variabler in the GO. In GO we put the variable type only at the end of the variable name like:
var variable_name varaiable_type
var muNumber int

we can define multiple variable by this way
var variable1, variable2, variable3 variable_type
var num1, num2 int
here all variable will the of the type vatiable_type

defining the variable with the initial value
var variable_name type = value
eg. var age int = 14

defining multiple variable with intial value
var num1, num2, num3 = 2, 3, 4
// same as num1 = 2, num2 = 3, num3 = 4

lets define three variable without the type and the var keyword with their initial values
vname1, vname2, vname3 := v1, v2, v3
Now it looks much better. Use := to replace var and type, this is called a brief statement.
its simple but it has one limitation: this form can only be used inside of functions. You will get compile errors if you try to use it outside of function bodies. Therefore, we usually use var to define global variables.

blank variable 
"_" is known as blank variable in GO because it's blank :). for eg:
_ , a := 10, 20 
here 20 given to a but 10 is discarded, we will use this on the later examples in real case

NOTE: GO will give compile time error if we didnt use the variable which are already defined.

GO - Introduction - Part 1

Image result for golang

What is "go"?
Go or golang is the new programming language developed by google for their most roboost and to manage the large scale application.

Why go?
It is lightweight and more managable and is awesome for the web services and last but not the least it is easy to learn.

What are its features?

  1. Support for environment adopting patterns similar to dynamic languages. For example type inference (x := 0 is valid declaration of a variable x of type int)
  2. Compilation time is fast.
  3. InBuilt concurrency support: light-weight processes (via goroutines), channels, select statement.
  4. Conciseness, Simplicity, and Safety
  5. Support for Interfaces and Type embedding.


But to make it more simpler following features haves been ommited


  1. Production of statically linked native binaries without external dependencies.
  2. No support for type inheritance
  3. No support for method or operator overloading
  4. No support for circular dependencies among packages
  5. No support for pointer arithmetic
  6. No support for assertions
  7. No support for generic programming

Angular 2 - Part 9 [Template-Driven Form]


In this tutorial we will create a template-driven form which will contain username, email, password and gender fields. which is as shown below:


here is the template-driven.html template file for this form:

<h2>Template Driven</h2>
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
  <div ngModelGroup = "userData">
    <div class="form-group">
      <label for="username">Username: </label>
      <input type="text" class="form-control"
             minlength="4"
             id="username"
             [(ngModel)]="user.username" name="username" required
             >
    </div>
    
    <div class="form-group">
      <label for="email">Email: </label>
      <input type="text" class="form-control"
             pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"
             id="email"
             [(ngModel)]="user.email" name="email" required
            >
    </div>
  </div>
  <div class="form-group">
    <label for="password">Password: </label>
    <input type="password" class="form-control"
           id="password"
           [(ngModel)]="user.password" name="password" required>
  </div>
  <div class="radio" *ngFor="let g of genders">
    <label>
      <input type="radio" [(ngModel)] = "user.gender" name="gender" [value]="g"> 
       {{g}}
    </label>
  </div>
  <button type="submit" class="btn btn-primary" >Submit</button>
</form>

Now let create a component for this form
template-driven.component.ts




import { Component, OnInit } from '@angular/core';
import {NgForm} from "@angular/forms";

@Component({
  selector: 'app-template-driven',
  templateUrl: './template-driven.component.html',
  styleUrls: ['./template-driven.component.css']
})
export class TemplateDrivenComponent{

  user = {
    username:"Yubraj",
    email:"yubraj@gmail.com",
    password:"asdfasdf",
    gender: "male"
  }
  
  genders = ["male", "female"];

  constructor() { }

  onSubmit(form: NgForm){
    console.log(form.value);
  }
}



What we did here is:
1. We created a html template
2. then we bind the html input with the user object which is in the component.
3. [(ngModel)]="user.username" .. is used to bind using two way data binding in the form
4. in the form we use (ngSubmit)="onSubmit()" to submit the form and #f is used to hold the form.
5. once submitting the form we will display the form value in the console.

What we need to implement is:
1. Only allow submission only when all the form data is valid.
2. show errors in the forms.

lets add some more attributes in the input fields i.e. #username, #email in order to represent the given field so we can show errors once it has been changed. Before that let us know that angular will add its own classes in the input field when running it, which are ng-valid if the form is valid and ng-invalid if the form is invalid as well as ng-dirty if the form value is changed and ng-touched if the form input
is touched or selected. which is as shown below:



so we modify the class ng-invalid and ng-valid which is used to highlight the input field if the data is not valid.

template-driven.component.css

.ng-invalid{ border-color: red; }
.ng-valid{  border-color: forestgreen; }

so once the input is invalid the border color will turn to red and on valid it will turn to green.


Adding the error message in the form:
we will add this line of code in the form to show the error in the form for each fields

<div class="alert alert-danger" role="alert" *ngIf="!username.valid">Invalid username</div>

here #username is used to reference the username input field in the form. So once it is invalid this above line will be displayed.  Similarly we can also make the submit button disabled if the form which is referenced by f. by this way:
<button type="submit" class="btn btn-primary" [disabled]="!f.valid">Submit</button>

lets check it out all together:

template-driven.component.html

<h2>Template Driven</h2>
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
  <div ngModelGroup = "userData">
    <div class="form-group">
      <label for="username">Username: </label>
      <input type="text" class="form-control"
             minlength="4"
             id="username"
             [(ngModel)]="user.username" name="username" required
             #username="ngModel">
    </div>
    <div class="alert alert-danger" role="alert" *ngIf="!username.valid">Invalid username</div>
    <div class="form-group">
      <label for="email">Email: </label>
      <input type="text" class="form-control"
             pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"
             id="email"
             [(ngModel)]="user.email" name="email" required
             #email="ngModel">
    </div>
    <div class="alert alert-danger" role="alert" *ngIf="!email.valid">Invalid email address</div>
  </div>
  <div class="form-group">
    <label for="password">Password: </label>
    <input type="password" class="form-control"
           id="password"
           [(ngModel)]="user.password" name="password" required>
  </div>
  <div class="radio" *ngFor="let g of genders">
    <label>
      <input type="radio" [(ngModel)] = "user.gender" name="gender" [value]="g"> {{g}}
    </label>
  </div>
  <button type="submit" class="btn btn-primary" [disabled]="!f.valid">Submit</button>
</form>


So here is the output:


This whole code is available in the github. check it out here 
#happyCoding


Angular 2 - Part 8 [ Forms ]


Forms in Angular has always been so interesting. We can do lots of stuffs in the forms using a little and simple techniques in angular. Forms are very important in the web applications. Forms are used to login, registrations and also for many stuffs. Dynamic web is not possible without the forms. In angular 1.x we have seen how angular helps us in developing much user friendly forms. In angular 1.x all the forms are template driven where as in angular 2 we can also create a data-driven forms too which are much easier and easy to learn as well.
So in the later two tutorial we will discuss on how we can create two types of forms using angular 2 which are: 
  1. Template-Driven: Most of the logic are included in the template 
  2. Data-Driven: Logic are applied via a internal implementations
Check it out the examples of each type of in the upcoming tutorials. 
#happyCoding


Anagram Solution in Java

Recently, I gave a technical interview one of the reputed software company in silicon valley. Here are the question and it's solution.

Problem: Anagram Problem

Anagram is a word that can be obtained by rearranging letter of the another word, using all the constituent letter exactly once.

Solution:




//Ouput will be

//{"apple", "perl"}, this is not anagram and to make we need to add: 2 character
  //{"lemon", "melon"} , this is anagram and it return 0

Angular 2 - Part 7 - [Routing]





This is the most interesting in the angular which makes our app super awesome. Using this techniques we can make our app single page application. In order to use this in angular 2 we need to use the @angular/router module. There are various steps to accomplish this feature in the angular app.

1. Set the base url
In every single page application we need to set the base URL in angular 2 we will do this using the
<base href="/" /> tag in the header section of the index.html page

2. Now we need to create a file in order to save all the routing information. So lets create a file call app.route.ts in the app directory. inside that we need to specify our routing information like:

import {Routes, RouterModule} from "@angular/router";
import {HomeComponent} from "./home/home.component";
import {VideosComponent} from "./videos/videos.component";
import {BlogsComponent} from "./blogs/blogs.component";
import {ContactComponent} from "./contact/contact.component";


const APP_ROUTE: Routes = [
  {path: '', component: HomeComponent},
  {path: "videos", component: VideosComponent},
  {path: "blogs", component: BlogsComponent},
  {path: "contact", component: ContactComponent}
];

export const routes = RouterModule.forRoot(APP_ROUTE);

here we are crating the routes as a constant value which stores all the routing information and is also ready to share with external elements using the export keyword. We have added this route information for the root using the forRoot().
so when ever we hit the root url the home componet will get called. similary if we hit url with /videos then the VideosComponent will get loaded and so on.

3. Now we need to import the route information in our app.module.ts file like:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { routes } from "./app-routing.module";
import { VideosComponent } from './videos/videos.component';
import { BlogsComponent } from './blogs/blogs.component';
import { ContactComponent } from './contact/contact.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    VideosComponent,
    BlogsComponent,
    ContactComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routes
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

4. Now everything is set up. Then we need to decide where to use the routes. In my condition I have used this in the appComponet using the <router-outlet></router-outlet>. Which means the dynamic views will be loaded on this tag and other parts will remains the same. here is the code for the app-componet.html:

....
....
<main class="mdl-layout__content">
    <div class="page-content mdl-grid portfolio-max-width">
          <router-outlet></router-outlet>
      </div>
</main>
...
...

Here the view will be loaded dynamically inside the <router-outlet> tag.


5. Now we are ready to use this module but still we cannot use the #/youlink like tag like in
angular 1. To call the router link from the html we need to use routerLink attribute in the link like this


...
<nav class="mdl-navigation">
        <a class="mdl-navigation__link" routerLink="/"><i class="material-icons">home</i> Home</a>
        <a class="mdl-navigation__link video" routerLink="/videos"><i class="material-icons">music_video</i> Videos</a>
        <!--<a class="mdl-navigation__link" routerLink="/"><i class="material-icons">developer_board</i> Experiences</a>-->
        <a class="mdl-navigation__link blog" routerLink="/blogs"><i class="material-icons">library_books</i> Blogs</a>
        <a class="mdl-navigation__link contact" routerLink="/contact"><i class="material-icons">mail_outline</i> Contact</a>
      </nav>
...

Now if we run the application then we can see our router in effect. Here we can add extra attribute called routerLinkActive inorder to change the style for our active link. for this we need to pass the css class.


You can see the full code of the application used in this totorial at here
Stay tuned for more awesome tutorial. happy coding :)