Monday, September 16, 2019

Block Chain concepts

1- Simple Blockchain with DATA+HASH+Previous Hash
Insimple work blockchain in a colloection of blocks containing data in form of Ladger arranged in a sequential manner with following attributes
1- Immutable :- Cannot be changed
2- Sequence is maintained by storing its own and previous block unique address. Hence the first block which did not have any previous block is termed as Genesis block i.e. PreviouBlock address=0;
3- In shot it can be terms as a system in which a record of transactions made in cryptocurrency are maintained across several computers that are linked in a peer-to-peer network.
2- CINA concept in internet.
Confidentiality: This can be expalined by taking simple word
Let say User A want to send message to User B using internet how we can make sure Message is not been read by User C on net. This is what confidentiality stand for. We need to make sure only User A and User B are the right candidate for reading this messages.
Integrity:-
Let say User A send message to User B how we can make sure the message is not been tempered in between. i.e. if User A send message "Hello USer B" to Uesr B then how we can make sure no thrid party User C had modified it to "Hello User B1".
Non repuditions:-
Let say User A send Message to User B and how we will make sure that the user A has only send this messsage and he will not be able to neglect his ownership on the same.
Authentication:-
During exchange between the messsage from User A and User B how we can make sure that message is properly authenticate from both parties.
3- Cryptography :- Symmentric and Asymmentric Solutions
Cryptography = Crypto means secret/hidden and graphy means To handle Confidentiality in the above network aspect we have Symmentric and Asymmentric crytography
Symmentric Key Crytography :-
User A --> Encrypt the message using his User A key --------------------------> USer B on receiving the message decrypt them using Using User A key.
Above scenario work perfectly right but assume if we had huge messsage to send different other user we have to maintain huge key.
Asymmentric Key Cryptography :- In this we have two key (1) Public Key = email id and (2) Private Key = password.
User A --> encrypt the message using his public key and send message to User B ----------------> User B decrypt the message using his Private key.
This issues solved our confidentiality concern on Network. But what about our other concern like Integrity, Non Repuditions and Authentications for that we will use below Asymmentric key cryptography.
User A encrypt the message using his Private Key + user B Public key and send message -----------------> User B decrypt the message first using his private key and then using User A public key.
4- BitCoin Example one complete flow
You might be thinking why BitCoin name is so much famous whenever we talk about BlockChain ... reason behind Bitcoin was the first to implement BlockChain in public mode for cryptography. Lets try to firs understand how they did it
Let say User A want to send money to the User B
User A --> Create a ledger i.e. Transection notes it may contains data like FROM:UserA , TO:UserB, Amount=10 Rs. etc ... information. This ledger is then encrypted using HASH algorithum (We will disscuss about different algorithm later HASH, MD etc). Then using Asymentric Key cryptography i.e. encrypt using privae key of sender + public key transection is send to the User B where in User B will decrypt the same using public key of Sender User A and his own private key. This way one complete transection is done.
In this case the process of claiming the do the work that involve solving of some mathematical problem so that we can be entitiled to encrypting the ledger using hash code and creating a block is called POW [Proof of work]. Person who do this is called Minner and process of adding the Block into the chain is called minning. FYI currently Bitcoin pay 12.5 point for this.
5- Nodes and its types.
Now lets go in details of Node for Block chain Cryptography. There are two main type of Nodes
1- Full Nodes :- On this full nodes your whole block chanin exist i.e. today bitcoin 130 GB and on this node we maitain and service new and old block. To do this we need huge CPU and GPU.
2- Partial Nodes :- such node i.e. even our mobiule we only use to do some transections.
6- Algorithem MD5 and SHA 512 
We talk above about the crytography hash algorithm. Important point to note HASH algorithm suggest what ever and how much data you give as input it will produce unique byte of string as an out put. To be more clear let say we use SHS512 algorithum as an input if we give all the character of encylopidea or simple string like "My name is siddharatha dhumale" as an output it will give simple string of 512 character. for SHAH64 algo we get string of 64 character. Additional we are sure that slight change in the data will definately change hash value. Further adding this hash code will be unique their is very very less chance that it may be same as other... In real scenario this is called hash collosion and we had another way to handle it. Will keep this part away from discussion as of now.
7- Markel Tree concept.
Now when we talk about the hash code it is good time to talk about the Market tree. Let say in one ledger we had 10 trasection do we need to have 10 hashcode or we can have single hash code for all this transection
h12345678
h1234 h5678
h12 h34 h56
h1 h2 h3 h4 h5 h6... h10
As shown in above structure we can store the final single hash code h12345678 as signed value. This process of getting unique hash code from multiple hash code is called Markel tree.
8- Disection of One single Block :- Timestamp, Version, Market Tree Root, POW [Difficulty Target, Nonce] and Previous Hash
Now lets go in details of what a single Bock contain. Basically it contains follwoing 5 items
1- Timestamp on which it is created.
2- Version
3- Markel Hash code
4- Two values from POW i.e. Difficulty Target and Nouce
5- Previous hash code.
9- Security i.e. 10 min example to add and update block
Biggest quesiton is how we can say that block are secure it may be possible that admin can change the data of the block ...agreed with you but issue will be as soon as any one change the data inside the blog its hash code will change ... rememeber one block hash code is also stored in second consecutive block as a PREVIOUS BLOCK hash code. so once original has code change then its consecutive chain get break. To make this valid user also need to reiterate all the consecutive cascade block and again recalculate their new has code as per this new values to main the chain again.
Now someone will say what's wrong in this process with the help of new super computer we can do this .. I agree with you but in BITCOIN to update or add new block in the chain it consume 10 min and huge POW. So consider if even though we have 10 blocks chain it will take approximately 100 min to change and in mean while new block will be added to the end ..and hence this will make such process next to impossible to do.

10- Consesus Algorithm
One of the important of Block chain in use of Consesus algotirhm. Let me give you in details what this means. Let say we have team of 5 people. Any decision which need to be taken will have to be approved by all 5 team member. Even if the single team memeber resist on the same the chain break. This is called taking consesus before acting. Remember ACID properties in EJB same is this :).
11- Type of Block Chain
There are three type of block chain
1- Public :- This type of block chain are public in nature means its data can be seen by all other and only few has write to modify it i.e. bitcoin.
2- Private :-This type of block chain are private in nature means its data can be seen by agreed and authenticated user only and only few among them has write to modify it. i.e. Banking Blockchain or corporate block chain etc.
3- Hybride :- This is amalgamation on both Public and Private block chain. Few of the block are private in nature and rest are public in nature.
Remember Public block are huge in size and as it is huge it will be difficult for any one to modify it.

12- HyperLedger
We had done enough of Bitcoin discussion till now. In current market you will be listening to new terms as HyperLedger.
Does hyperledge is new ledger, is it block chain, is it new type of block chain answe is NO
In simple word it open source collobrative effort to provide users with frame work and tool/ide to develop new blockchain. It is the owner ship of linux world.
13- Smart Contract
Simple word to define is the contract which is executed by the code which is written by us between the two party is called smart contract. I know you did understand what i means to say :) let me take example
Let say User A want to use a site ABC.com to get some item having many discount... concern here is we try to avoid using this ABC site due to its authentication issues might be possible it happen that ABC hier another company XYZ to send the product to my house. XYX give product to ABC but ABC did not send the product to me..how i can handle such scenario at run time. To do this i will have smart contract .i.e. if ABC deliver product to me then i will pay amount to XYZ. In this case i will be sure that at any given movement of time if the product did not reach my contract did not executed.
14- Etherium
Purpose is to have Platform for B2C businesses and generalized  applications and Confidentiality as Transparent and Mode of Peer Participation as Public/Private and Permissionless Network along with Consensus Mechanism as PoW Algorithm: Consensus is reached by mining and Programming Language asSmart Contracts written in Solidity and Cryptocurrency Built-in cryptocurrency called Ether
15- Disadvantage- CSR
- It is complex to understand
- It required huge resource to deal with CPU and GPU and mathemaical process to solve.
- It has 51% issues i.e. if a block chain has 51% false owner then it is wrong block chain.

Friday, September 13, 2019

Spring Boot Admin Server and Client

Create a spring boot application and following dependencise in pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Add following @EnableAdminServer in our main Server class
@SpringBootApplication
@EnableAdminServer
public class SiddhuSpringBootAdminServerApplication {
public static void main(String[] args) {
SpringApplication.run(SiddhuSpringBootAdminServerApplication.class, args);
}
}
Add following lines in your admin configuration properties
server.port = 9090
spring.application.name = adminserver
Compile the server and run the application
java -jar C:\Latest_workspace-sts-3.9.6.RELEASE\siddhu-spring-boot-admin-server\target\siddhu-spring-boot-admin-server-0.0.1-SNAPSHOT.jar

Image1Image2Image3Image4
And hit url
http://localhost:9090/#/
Image5
Now lets create the spring boot application admin client. Create an spring boot application and following dependencise in pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
@SpringBootApplication
public class SiddhuSpringBootAdminClientApplication {
public static void main(String[] args) {
SpringApplication.run(SiddhuSpringBootAdminClientApplication.class, args);
}
}
Add following lines in your admin configuration properties
spring.boot.admin.url=http://localhost:9090/
Image6Image7Image8Image9

java -Dserver.port=8888 -jar C:\Latest_workspace-sts-3.9.6.RELEASE\siddhu-spring-boot-admin-client\target\siddhu-spring-boot-admin-client-0.0.1-SNAPSHOT.jar
Compile the server and run the application and hit url
http://localhost:9090/#/
Image10

Wednesday, September 11, 2019

Spring Configuration server and client

In microservice concept where in we divide our big application into small services many time it happens that when we need to update any small service which has its own properties files in that case to load this individual microservice property files on deployment we need to restart the server on which this microservice is deployed. This make the production in downtime for this service. For application where in downtime is not preferred for microservice this architecture is good fit on the same.

To achieve this need Spring Boot configuration server, and we will have Spring Boot configuration client
Spring Boot configuration server :- This will store provide the ability for the spring boot microservice to have properties files of its client to be stored centralized in it. i.e. depending on the client name we store the different properties files inside this Spring Boot configuration server and at run time when Spring Boot configuration client run it take its respective file from this server. Only the thumb rule is the name of the property files is kept as similar to client service. Lets say we have client microservice as sid-client.jar then its respective property files can be named as sid-client.properties or sid-client.yml file.
In addition to individual client properties files we can also have one common application.properties in server which will be common for all the client.

Let us build simple Spring boot configuration server as shown below
Image1

Image2Image3Image4
You will able to see belwo code in pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
Add following tag to your mail spring boot applications to indicate this microservice as a configuration server.
@SpringBootApplication
@Configuration
@EnableAutoConfiguration
@EnableConfigServer

Image10

Please add follwing enteries in the properties files
Image5
#indicate the port number on which our configuration server is running
server.port=8889
#indicate the location of the properties files for the spring boot microservice client
spring.cloud.config.server.native.searchLocations=file:///C:/siddhu/configproperties/
#SPRING_PROFILES_ACTIVE=native
#spring.cloud.config.server.bootstrap=true
spring.application.name=siddhuconfigurationserver
#indicate profiles are active and it is stored in local system. We can store the configuration properties directly on GIT, SVN, Consul etc
spring.profiles.active=native
Inside C:/siddhu/configproperties/ we have created a property files names as sid-client.properties which will server our client microserver sid-client. for simple side we had just kept following text in that property file
first.message = This is first message for Sid-Client Microservice from Spring Boot Configuration server
Now compile the spring boot configuration server and run the jar file and see the browser text on hitting this url

Image6Image7Image8
Now hit the URL http://localhost:8889/sid-client/default/master and you will be see your client properties
Image9

Now lets create one Spring boot simple client that will refer to our above create spring boot configuration server for fetching its respective properties values i.e. from sid-client.
Note:- We need to make sure when we create the spring boot client we should name the client as sid-client so that it can fetched its properties from server.
Image11Image12
Make sure we have following entry in our pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Add following annotation in our mail class
@RefreshScope
Image14
We are using Spring thymeleaf java based library to creat web application hence we will also need spring-boot-starter-web package in the xml.
Now create static folder inside our resource folder along with CSS and templates folder as shown below
Image15Image16
Now compile the client application and run the jar as shown in below screen using different port
java -Dserver.port=8890 -jar sid-client-0.0.1-SNAPSHOT.jar

Image17
Now hit the url http://localhost:8890/ and you will be able to see the value from the text that is described in server property files.
Image18

Monday, September 09, 2019

Spring Zuul Server

Zuul Server is provided by Spring framework to proxy your request url. It handles all the requests and does the dynamic routing of microservice applications. The Zuul Server is also known as Edge Server.
For Example, your url having this pattern /api/login is mapped to the login service and /api/user is mapped to the user service and Zuul Server dynamically routes the requests.
Lets first create a Zuul server
Iamge1
Image2Image3Image4Image5

Have below given entries in your application.properties
spring.application.name = zuulserver
zuul.routes.json.path = /todo/**
zuul.routes.json.url = https://jsonplaceholder.typicode.com/todos/
server.port = 8111
Image6
Lets try to understand what each entry is saying
'- spring.application.name define the name of the Zuul sever
'- zuul.routes.products.path specify the url that will be maped for rounting
'- zuul.routes.products.url configure the original url that is going to be hit for taking the data
'- server.port port on which zuul sever is going to listen.
Now lets compile the maven application and create a spring boot jar and run the same using below command
java -jar siddhu-zuul-example-server-0.0.1-SNAPSHOT.jar
Image7Image8
If you see above the original URL which is hit to get the data is https://jsonplaceholder.typicode.com/todos/ but the url that we hit on the broswer is http://localhost:8111/todo/3.
Zuul it self will take care of proxing the url and redirecting to perticular server.

Friday, September 06, 2019

Spring Eureka for Microservice

Spring Eureka Server is an application that maintains information about all client-service applications i.e. In SOA architecture where we are trying to decompose our application in many Microservice with a need where in one microservice need to contact another microservice we need to Manuel maintain all the required information like IP address, PORT etc but Eureka server does this for us. Eureka server knows all the client applications running on each port and IP address. All Microservice need to register themself to Eureka Server so that they are available to the client. Eureka service is also known as Discovery Server. So in short the Eureka server is nothing but a service discovery pattern implementation, where every microservice is registered and a client microservice looks up the Eureka server to get a dependent microservice to get the job done.

Let's create Spring Eureka Server as shown below. We are using STS IDE.
Image1
Image2

Image3
Change Property files
#Below line tell this is server and not the client
eureka.client.registerWithEureka = false
#Indicate no need to fetch client registry
eureka.client.fetchRegistry = false
#Operate on Port 8761.
server.port = 8761
Image4


Add anotation to main Spring boot class to inform that this is Eureka Server.
Image5
Once you successfully run below maven command you will get *.jar files.
mvn clean install
This is our Server jar and now run your Eureka Server jar

Image6
Note :- if you java.lang. TypeNotPresentException: Type javax.xml.bind.JAXBContext Exception check your JDK version.
Java 7 version: Included and Working
Java 8 version: Included and Working
Java 9 version: Deprecated
Java 10 version: Deprecated
Java 11 version: Removed
so either used JDK8 or lower version.
Now lets create a another Microservice as a client and register it with our above created Eureka Server.
Image7

Image7
Image8

Change Property files
#Give the address of server where he need to register itself.
eureka.client.serviceUrl.defaultZone = http://localhost:8761/eureka
#Communication can be done with the help of IP address.
eureka.client.instance.preferIpAddress = true
#Itendified by below given name by Eureka Server and other client.
spring.application.name = eurekaclient

Image9

Add annotation to main Spring boot class to inform that this is Eureka Server.

Image10
Once you successfully run below maven command you will get *.jar files.
You also need add following items in the pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Image11
mvn clean install
Now runt the created jar file using below command
Note: As I am using different port 8888 i need to use below comments to start the spring boot eureka client.
java -Dserver.port=8888 -jar siddhu-eureka-example-client-0.0.1-SNAPSHOT.jar
Run following command on url http://localhost:8888/
Image12Image13

Monday, August 12, 2019

Simple JAVA base Graphql Subscription Example

One of the best use of GraphQL is its ability to react onspot i.e. as in old JDK we have the concept of Observable Class and Observer Interface where in whenever any observable class change it notify all the observer class to perform some action. Same is done using RXJAVA
package com.siddhugraphql.java.siddhuuserdetails.util;
import com.siddhugraphql.java.siddhuuserdetails.resolvers.User;
import io.reactivex.Observable;

public class RxJava2Example
{
public static void main(String[] args)
{
User obj = new User("One","two",3);
//producer
Observable<User> observable = Observable.just(obj);

//consumer
//Consumer<? super String> consumer = System.out::println;
SiddhuConsumer objSiddhuConsumer = new SiddhuConsumer();
//Attaching producer to consumer
observable.subscribe(objSiddhuConsumer);
}
}
package com.siddhugraphql.java.siddhuuserdetails.util;
import com.siddhugraphql.java.siddhuuserdetails.resolvers.User;
import io.reactivex.functions.Consumer;
public class SiddhuConsumer implements Consumer<User> {
@Override
public void accept(User t) throws Exception {
// TODO Auto-generated method stub
System.out.println("--------------------"+t.toString());
}

}
As shown above for RX we have
Producer :- That produce the data and emit. It use observable class and subscribe the Consumber
Consumer :- That consume the data and work on it. For doing this it implements Consumer interface and override accept() method.

Now lets come to our GraphQL example. Lets say we want to demo an subscription example where in when we do any mutation operaion i.e createUser it will be catch by our consumber and will display it on the screen
Let me show you the screen shot
Image1
Through Post man we hit the Graph Mutation request.

Image2
Below image shows that as soon as the mutation request is fired we find the data present in the UI

Image3
Hurrey we are done with simple GraphQL Subscription example
Now lets go in details of what we had done in code
You can download the complete running example from below GIT location

https://github.com/shdhumale/siddhu-user-details

We have use the inbuild example of graphql Subscrition example html to request subsription request.
1- index.html
Following lines are modified to hit our Subscription request
function subscribeToStocks() {
var exampleSocket = new WebSocket("ws://localhost:9090/stockticker");
networkBlip();
exampleSocket.onopen = function () {
networkBlip();
console.log("web socket opened");
var query = 'subscription userSubscription { \n' +
' newUser {' +
' id\n' +
' name\n' +
' age\n' +
' }' +
'}';
var graphqlMsg = {
query: query,
variables: {}
};
exampleSocket.send(JSON.stringify(graphqlMsg));
};
var STOCK_CODES_UPDATES = {};
exampleSocket.onmessage = function (event) {
networkBlip();
var data = JSON.parse(event.data);
console.log("data----------------->"+data);
var age = data.newUser.age;
var id = data.newUser.id;
var name = data.newUser.name;
console.log("id----------------->"+id);
console.log("age----------------->"+age);
console.log("name----------------->"+name);
var htmlStr = '';
htmlStr += '<div class="stockWrapper">';
htmlStr += '<span class="stockSymbol"> ' + id + ' </span>'
htmlStr += '<span class="stockSymbol"> ' + name + '</span>';
htmlStr += '<span class="stockSymbol"> ' + age + '</span>';
htmlStr += ', ';
htmlStr += '</div>';
$('.stockTicker').html(htmlStr)
};
}
window.addEventListener("load", subscribeToStocks);
First file which is hit when we run this url on the browser http://localhost:9090/index.html is SiddhuWebSocketConfig
From here we execute SiddhuWebSocketHandler and initialize SiddhuGraphqlPublisher.
SiddhuWebSocketHandler class is used to make the websocket connection and listen to that socket if any request is coming
SiddhuGraphqlPublisher class we read our schema.graphqls and execute it so that we can use this code as our Graphql server code to serve the request.
When we execute our SiddhuUserDetailsApplication spring applications
GraphQLProvider execute our schema.graphqls so that it will be available for all the request given by client.
In our mutation call we make a call publish with our User object.
//by siddhu for Mutation start[
public DataFetcher createUserDataFetcher() {
System.out.println("here reached............");
return dataFetchingEnvironment -> {
String name = dataFetchingEnvironment.getArgument("name");
System.out.println("here reached..name.........."+name);
int age = dataFetchingEnvironment.getArgument("age");
System.out.println("here reached..age.........."+""+age);
objUser = new com.siddhugraphql.java.siddhuuserdetails.resolvers.User("sid-41",name,age);
SiddhuGraphqlPublisher.STOCK_TICKER_PUBLISHER.publish(objUser);
return objUser;
};
}
//by siddhu for Mutaion end]
finally in our UserPublisher constructor
public UserPublisher(){
Observable<User> commentUpdateObservable = Observable.create(emitter -> {
this.emitter = emitter;
});
ConnectableObservable<User> connectableObservable = commentUpdateObservable.share().publish();
connectableObservable.connect();

publisher = connectableObservable.toFlowable(BackpressureStrategy.BUFFER);
}

public Flowable<User> getPublisher() {
return publisher;
}

public void publish(final User user) {
emitter.onNext(user);
}
that's it and you will be able to see our subscription example is running with simple java code.

Image4