Search This Blog

Friday 12 April 2019

Angular PUT request sample code for rest service

Main component code
====================
@Component({
  selector: 'name',
  template: require('./name.template.html'),
  providers: [NameService],
})

export class NameComponent implements OnInit {

constructor(private _ns: NameService) {
      -------------
  -------------
    }

ngOnInit() {
----------
----------
}

saveNameDetails(obj) {
let dataList = {};
dataList['name'] = obj['name'];
_ns.save(dataList);
}
}

service component code:
========================
import { Response, Http } from '@angular/http';
--------------------
--------------------
@Injectable()
export class NameService {

constructor(private _http: Http) { }

  save(body) : Observable<any> {

    return this._http.put(URL, body, this.headerOptions)
      .map(this.extractData)
      .map(this.doAction)
      .catch(this.handleErrorMessage);
  }

  private extractData(res: Response) {
    return res;
  }

  private doAction(response: any) {
    return response;
  }

  private handleErrorMessage(errorObj: Response | any) {
    let _body = JSON.parse(errorObj['_body']) || {};
    let errorMessage: string;
    switch (errorObj.status) {
      case 400:
      case 401:
        errorMessage = _body['error'];
        break;
      case 404:
        break;
    }
    return Observable.throw(errorMessage);
  }
  ---------------------
  ---------------------
  }

Monday 20 August 2018

Angularjs 2

Angularjs 2

It is very powerful and latest advanced language makes easy development;it gives full control on business logic which is related to specific HTML page. It provides predefined directives and makes developers job easy. It is simply like Java. This language is very easy for java developers to learn.
It is streamlined front end development and editor support to show compilation errors.

It provides library modules. These starts with @angular prefix and these should be installed using npm package manager Ex: npm install --save react

Each and every angularjs 2 application have a bootstrap root component it hosts all the application views and this should be specify with @NgModule under meta-data.

Sample bootstrap root component:
import { NgModule }      from '@angular/core';
...other imports...
@NgModule({
  imports:        [ imported components with comma separated ],
  providers:     [ providers with comma separated ],
  declarations: [ ------------------------------ ],
  exports:         [ ------------------------------ ],
  bootstrap:      [ ------------------------------ ]
})
export class AppModule { }

Angulajs 2 uses type script so files will be saved with .ts extension. File contains might three sections
such as 1) imports - we will import pre defined angularjs directives and user defined components  etc, 2) meta-data - this information is about class 3) class - it contains member variables, constructor, life cycle methods and user defined  methods.

This is component based language and it separates clearly HTML code and model code.

Component:
Component through which we can access html elements. Implement html elements events methods in component. Component is similar to class only but it has life cycle methods and constructor. Angularjs2 provides predefined directives and we can import them on demand to use.

Component controls the view and provides functional support for events of view. Need to define for functionality for each and every event of the view in component.
Client side business logic can be implemented  as service which we can use wherever we want.

Member variables of the component can be mapped to html controls.

The class must be annotated with @Component in the meta data section then only AngularJs treats as component otherwise it is a simple class

Sample component syntax:

import { Component, OnInit, ngAfterViewInit,ngOnDestroy } from '@angular/core';


import { HelloService } from './hello.service';

@Component({
  selector: 'hello-world-app',
  templateUrl: 'hell-world-app.html',
  styleUrls: ['hell-world-app.css'],
  providers: [HelloService]
})

export class HelloWorldAppComponent implements OnInit {
  var title:string = 'Hello World';

  constructor(private _helloService: HelloService) { }

  userdefeined methods  to handle html events

  ngOnInit() {// Initializes the component
     ---------------
     ---------------
     ---------------
  }
  ngAfterViewInit() { //this method will be called after rendering component and its child components
--------------
--------------
--------------
  }
  ngOnDestroy() {// this method will be called before destroying component
--------------
--------------
--------------
  }
}

component have name, member variables which are available to all component methods and can be linked to html elements, and member methods which can be linked to html element events.

Angulajs-2 files need to save with .ts as it uses typescript.

 selector: 'hello-world-app'
        hello-world-app will be used to include this component in other html pages.

class HelloWorldAppComponent
       HelloWorldAppComponent it will be used to include this component in other components.

 template : It allows to write html code in the component between backticks. This is not good pactice.
templateUrl : it will be used to specify html file

providers: we have to specify here with comma separated if component required any other services.

export: if you want import this component in other components then then it must be defined with export key word.

Development story starts using npm install, npm start commands and visualstudio editor

Life cycle hooks:


ngOnInit:
------------
It will executed only once in the component creation to do initialize; It will be executed after constructor and after first ngOnChanges execution.

ngOnChanges :
--------------------

This method will be execute whenever input data properties resets and this method will be called before ngOnInit. Previous and current values are available for this method.

ngAfterViewInit:
----------------------
In Parent component - This method will be called after rendering child components and parent component.

In Child component -
      Case 1: This method will be called after rendering child component
      Case 2: Special case suppose in your application back and forward buttons implemented and     while navigating between components and changed input then it renders child components again
  so then also it will be executed (We used this functionality in child components only).

Routes in angularjs2:
----------------------------

We have to put base anchor tag in index.html, need to pass as array ROUTER_PROVIDERS to bootstrap in boot.ts, need to define router links and router outlet in app component, need import ROUTER_DIRECTIVES and RouterConfig in app component, need to define RouterConfig which is decorator with all the routes.

step 1: <base href="/">       in index.html

step 2: bootstrap(AppComponent, [ROUTER_PROVIDERS]     in boot.ts

step 3: In app component html under header need to specify router links
            <nav>
                <a [routerLink='routerLink1']> Click Link1</a>
                <a [routerLink='routerLink2']> Click Link2</a>
            </nav>

step 4: In app component html need to specify router outlet
            <div>
               <router-outlet></router-outlet>
           </div>
step 5: Need to mention ROUTER_DIRECTIVES in directives section.

step 6: Need to define RouteConfig decorator in app component
         
           @RootConfig([

                     {path:"link1", name:"routerLink1", component:"UserDefinedComponent1", useAsDefault:"true" },

                    {path:"link2", name:"routerLink2", component:"UserDefinedComponent2", }

             ])


Site for complete documentation: https://angular.io 

Wednesday 8 August 2018

B star tree structure

B star tree structure



Journey of byte

Journey of byte

Step 1: Whenever user tries to open file in system or save file; application manger sends request to file manger.
Step 2: The file manger handovers the request to I/O manager.
Step 3: The I/O manger handovers the request to disk manager.
Step 4: Disk manger reads the contents of disk and fillis into buffer and handover back to I/O. I/O to file  manger. File manager to application. Finally Application shows the file contents.
Step 5: Disk manager reads contents from sector. sector is set of bytes. And file is not stored into continues sectors. Read write head is responsible to read or write contents from the disc so read write head has to identify starting of the sector and ending of the sector. After reading or writing contents into sector it has to identify sector ending so it is required some time. As well it has to identify next sector staring this also required some time. So while storing file contents into disc; it writes contents into first sector and leaves some sectors and it writes; it continues like that. So one spindle of the disc it reads or writes into multiple sectors.

Each sector contains the information about ending of the sector and next sector starting.


Tuesday 3 July 2018

Parallel / Old GC, CMS, G1 GC - Java 7, Meta space , HashMap enhancement , streams- Java 8

Parallel / Old GC, CMS, G1 GC - Java 7, Meta space , HashMap enhancement  streams- Java 8


Types of garbage collectors in Java - serial GC - Jvm uses during garbage collection & mark and delete objects

Parallel GC similar to serial GC but multiple threads are used to speed up garbage collection & n number of threads based on young generation and one thread for old generation

Parallel Old GC - similar to parallel GC but it has n number of threads for young generation and n number of threads for old generation

Concurrent Mark Sweep -  these will do garbage collection for old generation; tries to minimize the pause which happens garbage collection; and uses concurrent mechanism

G1 GC - It is introduced to replace CMS GC. It is a parallel concurrent & incrementally compacting low pause collector. There is no concept of old and young  generation objects. It divides the space inside the heap into multiple equally sized regions and whenever there is grabage collection involved it first collects the region which have lesser live data.

G1 GC - Jvm 7 and above versions supports.
Gc will do Mark , Delete and Compacting.

Mark: Initially GC marks all objects in the heap reachable or unreachable.

Delete: GC deletes the all unreachable objects in the heap.

Compacting: GC deleted all unreachable objects from various memory locations so it arranges the all the reachable objects in side by side memory locations sequentially.

Meta space : PermGen space replaced with meta space in java 8. It is allocated by OS so there is no OutOfMemoryException from java 8 onwards. But there is drawback to take whole server space. Different sizes can be specified for meta space like java heap space.

HashMap 8 enhancement - we all know hashmap contains table and maintains objects in the linked list form for collision of hash code for different keys for same bucket. But in java 8 if objects crossed threshold value  in the hash bcket, then automatically arranges linked list objects into balanced tree format to improve performance.

Jav8 streams - There are two types of streams introduced in it such as sequential stream and second one is parallel stream. Through those java supports functional programing.

Sequential stream - which creates stream object for   for collection elements and processes one thread.

Parallel streams:  This uses Fork Join Thread Pool Framework to processes collection object elements. Collection elements divided into sub tasks and fork thread pool threads executes the sub tasks and joins the results of all subtasks and finally sends back the result. It maximises the cpu cores utilisation and maximises the throughput.
These improves performance drastically of the application if ur playing with huge amount of data.



Container creates thread object for dispatcherservlet which is extended from HttpServlet and all singleton beans shared among all threads. Note no threads will be created for singleton object.

Sunday 5 November 2017

Converting JAXB Object to SOAP Request XML - converting SOAP Response XML to JAXB object - and Binding Service call

Converting jaxbobject to XML 

public String jaxbObjToXML(JAXBEntityClassName jaxbObj)  throws JAXBException{
         JABContext jaxbContext = JAXBContext.newInstaance(JAXBEntityClassName.class);
        Marshaller marshaller = jaxbContext .createMarashaller();
        //optional
        marshaller .setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "schema_URL");
        marshaller .setProperty(Marshaller .JAXB_FORMATED_OUTPUT, true);
       StringWriter sw  = new StringWriter();
       marshaller.marshal(jaxbObj, sw);
       return sw.toString();
}


Converting jaxbobject to XML using QName when JAXBEntityClassName  does not contain root element.


public String jaxbObjToXML(JAXBEntityClassName jaxbObj)  throws JAXBException{
         JABContext jaxbContext = JAXBContext.newInstaance(JAXBEntityClassName.class);
        Marshaller marshaller = jaxbContext .createMarashaller();
        marshaller .setProperty(Marshaller .JAXB_FORMATED_OUTPUT, true);
       StringWriter sw  = new StringWriter();
       marshaller.marshal(new JAXBElement<JAXBEntityClassName>(new QName("schema_URL",          "JAXBEntityClassName"), JAXBEntityClassName.class, null, jaxbObj) sw);
       return sw.toString();
}

Converting XML to JAXB Response object

public JAXBEntityResponseClassName  xmlToJAXBObject(String xml) throws JAXBException, XMLStreamException {
             XMLInputFactroy xif  = XMLInputFactroy.newFactroy();
             ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
             XMLStreamReader xsr = xif.createXMLStreamReader(bis);
            JAXBContext jaxbContext = JAXBContext.newInstance("com.xyz.jaxb") //jaxb entities                      package need to give in double quotes
           Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
           JAXBElement<JAXBEntityResponseClassName> jaxbResponseObj
           = unmarshaller.unmarshal(xsr, JAXBEntityResponseClassName.class);
         return jaxbResponseObj.getValue();
}


Binding Service calling:

public ClientToServiceClass {

      private ServiceClass service;

      public ClientClass(String wsdlURL, String userName, String password) throws IOException{
          QName qname = new QAName("schema_URL", "QNAME_IN_OBJECT_FACTROY");
          URL url = new URL(wsdlURL);
          HandlerReslover handlerReslover = new ClientUsernameTokenHandler.Reslover(username,               password);
          Service endpoint = service.creaate(wsdl, qname);
          endpoint.setHandlerReslover(handlerReslover);
          service = endpoint.getPort(ServiceClass.class);
      }
   
      public ResponseClass callServiceWithBindingService(String bindingServiceURL) throws Exception          {
          BindingProvider bp = null;
          bp = (BindingProvider) service;
         bp.getRequestContext().put(BindingProvider.ENDPOIT_ADDRESS_PROPERTY,                              bindingServiceURL);
         //Prepare JAXB Request object
         JAXBRequest jaxbRequest = new JAXBRequest();

        ResponseClass responseObj = service.getServiceMethod(jaxbRequest);
        return responseObj;
     }
}


wsimport command: 

wsimport -p com.abc.xyz -keep -verbose wsdl_URL







Wednesday 8 March 2017

Project read error - pom.xml in eclipse


Project read error pom in eclipse

=====================================

1) Window --> Preferences --> Maven--> User Settings - set proper
settings.xml in which verify user name password and .m2 path of the system

2) And Project right click - Maven - Run as - mvn package

Monday 24 October 2016

hashCode and equals contract in java

public boolean equals(Object obj),public int hashCode() are methods of Object class.


Equals Demo Without Hashcode:
-----------------------------
import java.util.HashMap;

public class Emp{
private String name;

public Emp(String _name) {
name = _name;
}

public boolean equals(Object obj) {
if(obj==null) return false;
if (!(obj instanceof Emp))
return false;
if (obj == this)
return true;
return this.name.equals(((Emp) obj).name);
}
}

public class EqualsDemoWithoutHashcode {

public static void main(String[] args) {
Emp emp1 = new Emp("XYZ");
Emp emp2 = new Emp("ABC");

//HashMap stores Emp type and its salary
HashMap<Emp, Integer> m = new HashMap<Emp, Integer>();
m.put(emp1, 1000);
m.put(emp2, 20000);
System.out.println(m.get(new Emp("XYZ")));
}
}

In this case emp1 and emp2 hashcodes are different and equals also returned false as data different of the objects. And emp1 and emp2 are placed into hashmap. Here Object class hashcode function will be used to generate hash code. So while retrieving object from hashmap again it uses Object class hashcode function and it will not give any surety for user defined class objects to create same hash code for the object while retrieving. So if hash code is not same then it gives inconsistent data.


Similarly Suppose implemented hash code function and equals method not implemented. It will stores duplicate keys because it uses Object class equals method and it will not compare data of the object but it compares references. So references are not same so it stores duplicate keys.


HashMap stores internally data in table format and it uses hashcode function and equals method. To store objects in hashmap first it generates hash code and based on the hash code it stores in the bucket. Suppose same hash code is generated for two key objects then it uses equals method whether both key objects are same or different. If two key objects are different then it maintains multiple objects in the same bucket with same hash code.

Thursday 13 October 2016

Proxy design pattern

Proxy design pattern

It is structural design pattern; It is place holder for original object and limits the access to it. This provides interface original object functionality to clients.This represents functionality of another class which is sensitive remote target object.
Client deals with Proxy class which delegates to the original object (target object).

Proxy class which holds the original object and provides interface and  delegates to the target.

Proxy Demo:

BankAccount.java
------------------------
class BankAccount {
int accountNo;
String name
                float amount;
String accountType;
String bankName;
String address;
int customerID;
           
              public BankAccount() {
accountNo = 1111111111111;
name = "abc"
                amount = 10000;
accountType = "Savings";
bankName = "XYZ Bank";
address = "D No-111 efgh street";
customerID = 12345;
}

public boolean withdraw(float _amount) {
boolean isWithdrawSuccess = false;
if (amount > 0 && amount >= _amount) {
amount -= _amount;
isWithdrawSuccess = true;
}
return isWithdrawSuccess;
}

public void deposit(float _amount) {
amount += _amount;
}
public int getAccountNo() {
return accountNo;
}

public void setAccountNo(int _accountNo) {
accountNo = _accountNo;
}

public String getName() {
return name;
}

public void setName(String _name) {
name =_name;
}

  public float getAmount() {
return amount;
}

public void setAmount(float _amount) {
amount = _amount;
}

public String getAccountType() {
return accountType;
}

public void setAccountType(String _accountType){
accountType= _accountType;
}

public String getBankName() {
return bankName;
}

public void setBankName(String _bankName) {
bankName = _bankName;
}

public String getAddress() {
return address;
}

public void setAddress(String _address) {
address = _address;
}

public int getCustomerID() {
return customerID;
}

public void setCustomerID(int _customerID) {
customerID =_customerID;
}

}

 interface OrderOperations {
  AccountDetails getAccountDetails();
  void  bookOrder(float orderAmount, String customerType);
  void unbookOrder(float orderAmount, String customerType);
}
AccountDetails.java
---------------------------
class AccountDetails {
String name;
float amount;
public String getName() {
return name;
}
public void setName(String _name) {
name =_name;
}
public float getAmount() {
return amount;
}
public void setAmount(float _amount) {
amount = _amount;
}

}
ProxyOrderOperationsImpl.java
-------------------------------------------
class ProxyOrderOperationsImpl implements OrderOperations {
BankAccount customerAccount;
ProxyOrderOperationsImpl() {
customerAccount = new BankAccount();
}

public AccountDetails getAccountDetails() {
AccountDetails  accountdetails = new AccountDetails();
System.out.println("***Account Details***");
System.out.println("Name:::" + customerAccount.getName());
accountdetails.setName(customerAccount.getName());
System.out.println("Amount:::" + customerAccount.getAmount());
accountdetails.setAmount(customerAccount.getAmount());
   return accountdetails;
}

public void  bookOrder(float orderAmount, String customerType) {
if (orderAmount > 5000) {
if("Regular".equalIgnoreCase(customerType)) {
orderAmount-=500;
} else {
orderAmount-=100;
}
}
boolean isBookOrder = customerAccount.withdraw(orderAmount);
if (isBookOrder) {
System.out.println("Order Booking is successful...");
} else {
System.out.println("Order Booking is un-successful...");
}

}
public void unbookOrder(float orderAmount, String customerType) {
        if (orderAmount > 5000) {
if("Regular".equalIgnoreCase(customerType)) {
orderAmount-=500;
} else {
orderAmount-=100;
}
        }
boolean isUnbookOrder = customerAccount.deposit(orderAmount);
if (isUnbookOrder ) {
System.out.println("Order Unbooking is successful...");
} else {
System.out.println("Order Unbooking is un-successful...");
}
}

}
PrxoyPatternDemo.java
--------------------------------
public PrxoyPatternDemo {
public static void main (String args[]) {
ProxyOrderOperationsImpl orderOperations = new ProxyOrderOperationsImpl();
orderOperations.getAccountDetails();
orderOperations.bookOrder(3000, "Regular");
orderOperations.unbookOrder(3000,"Regular");
}
}


Monday 10 October 2016

Production issue analysis

Production issue analysis

Step 1: Try to reproduce issue in development environment, integration environment, and pre-production environment.

Step 2: If Production issue is not reproducible in above step, then we will get logs for production and we will analyse the logs to understand the issue; we will look is there any error message related to issue.

Step 3: We will see for "is there any differences in configuration between production and lower environment" and deployment version difference.

Step 4: if above three steps fails then we will  get production installed ear file or war file and we will deploy in lower environment and try to reproduce the issue.

Step 5: If above four steps fails then we will request for data-dump from production and we will load that into lower environments and try to reproduce the issue in lower environment.


Service locator design pattern

Service locator design pattern: 
It is used when we want to locate various services objects like JNDI. It caches the service objects. It looks first for service objects its cache. It access service object from its cache if it exists in cache otherwise  it lookup service object, it adds to its cache and returns service object.

Service - This is the actual service which process the request.

Service Locator - This is central point to get service object and it caches the services.

Cache - This holds references of services to reuse them.

Client - This calls the ServiceLocator and rceives the service object.

Servicelocator Demo:

BankService.java
-----------------------
public interface BankService {
 public String getServiceName();
 public boolean createAccount(CustmorInfo custInfo);
 public boolean deleteAccount(CustmorInfo custInfo);
}

AbcBankService.java
----------------------------
public class AbcBankService implements BankService {
public boolean createAccount(CustmorInfo custInfo){
boolean accountCreationStatus = false;
if (custInfo.getName()!= null) {
System.out.println("Account is created successfully in AbcBank");
accountCreationStatus = true;
}
retur accountCreationStatus;
}
public boolean deleteAccount(CustmorInfo custInfo) {
boolean accountDeletionStatus = false;
if (custInfo.getName()!= null) {
System.out.println("Account is delted successfully from AbcBank");
accountDeletionStatus = true;
}
retur accountDeletionStatus;
}
    @Override
public String getServiceName() {
    return "AbcBankService";
}
}

XyzBankService.java
----------------------------
public class XyzBankService implements BankService {
public boolean createAccount(CustmorInfo custInfo){
boolean accountCreationStatus = false;
if (custInfo.getName()!= null) {
System.out.println("Account is created successfully in XyzBank");
accountCreationStatus = true;
}
retur accountCreationStatus;
}
public boolean deleteAccount(CustmorInfo custInfo) {
boolean accountDeletionStatus = false;
if (custInfo.getName()!= null) {
System.out.println("Account is delted successfully from XyzBank");
accountDeletionStatus = true;
}
retur accountDeletionStatus;
}
    @Override
public String getServiceName() {
    return "AbcBankService";
}
}
CustmorInfo.java
------------------------
class CustmorInfo {
String name;
String address;
String accountType;

public setName(String _name) {
name = _name;
}
public String getName {
rturn name;
}
public void setAddress(String _address) {
address = _address;
}
public String getAddress() {
return address;
}
public void setAccountType(String _accountType) {
accountType = _accountType;
}
public String getAccountType() {
return accountType;
}
}

Cache.java
--------------
import java.util.ArrayList;
import java.util.List;
public class Cache {

  private List<BankService> services;
    public Cache(){    
services = new ArrayList<BankService>();
}
    public Service getService(String serviceName){
        for (BankService service : services) {
if(service.getServiceName().equalsIgnoreCase(serviceName)){
           System.out.println("Returning cached  " + serviceName + " object");
           return service;      
}    
}    
return null;
}
 
public void addService(BankService newService){    
boolean exists = false;          
for (BankService service : services) {      
if(service.getServiceName().equalsIgnoreCase(newService.getName())){          
exists = true;      
}    
}    
if(!exists){      
services.add(newService);    
}
}
}
ServiceLocator.java
--------------------------
public class ServiceLocator {
private static Cache cache;
    static {
     cache = new Cache();  
}
    public static Service getService(String serviceName){
      Service service = cache.getService(serviceName);
      if(service != null){      
return service;    
}
      //Make lookup calls to get service objects from JNDI  
Service service1 = BankServiceFactory.buildService(serviceName);
try {    
cache.addService(service1);
} catch (InvalidBankServiceException exception) {
System.out.println("Requested service is invalid" + exception);
}  
return service1;
}
}
BankServiceFactory.java
--------------------------------
class BankServiceFactory {
public static BankService buildService(serviceName) throws InvalidBankServiceException{
if ("AbcBankService".equalsIngnoreCase(serviceName)) {
return new AbcBankService();
} else if ("XyzBankService".equalsIngnoreCase(serviceName)) {
return new XyzBankService();
} else {
throw new InvalidBankServiceException("Requested bank service is invalid:::"+serviceName);
}

}
}

InvalidBankServiceException.java
---------------------------------------------
class InvalidBankServiceException{
InvalidBankServiceException(String s) {
     super(s);
}
}
ServiceLocatorDesignPatternDemo.java
----------------------------------------------------
public class ServiceLocatorDesignPatternDemo {
public static void main(String[] args) {    
Service service = ServiceLocator.getService("AbcBankService");
if (service != null) {    
service.createAccount();
}    
service = ServiceLocator.getService("XyzBankService");    
if (service != null) {    
service.createAccount();    
}
service = ServiceLocator.getService("AbcBankService");    
if (service != null) {    
service.deleteAccount();    
}
service = ServiceLocator.getService("XyzBankService");    
{
service.deleteAccount();  
}
}
}















Sunday 9 October 2016

Singleton design pattern Demo

                                  Singleton design pattern Demo
Singleton pattern ensures that only one instance of the class exists in the java virtual machine.It provides a way to access instance of the class through factory method.

synchronized block - In multi thread environment; it gives access to single thread and it ensures that only one instance exists to class
final in class declaration - It will not allow to create subclass; privents inheritance
Colonable - need to override which should not allow to colone the object
Serializable - need to override readReslove method which should not create another object while desralizing object

final public class SingletonClass implements Cloneable, Serializable{
   
    private static SingletonClass myObj;
   
    //Private constructor
   
    private MySingletonClass(){
       
    }
   
    //A static method to get instance.
    public static MySingletonClass getInstance(){
synchronized {
                if(myObj == null){
     myObj = new SingletonClass();
}
        }
        return myObj;
    }
   
    // clone method overridding
    public Object clone() throws  CloneNotSupportedException{ 

return new CloneNotSupportedException("Clone Not Supported Exception.......");
    }
   
    public Object readResolve() {
      return SingletonClass.getInstance();
   }
   private void writeObject(ObjectOutputStream oos) {
      try {
      ----------------
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   private void readObject(ObjectInputStream ois) {
       try {
       ----------------
       } catch (Exception e) {
          e.printStackTrace();
       }
   }  

   @Override
   public String toString() {
      return "Singleton toString....";
   }
}

public class MySingletonDemo {
    public static void main(String a[]){
        MySingletonClass st = MySingletonClass.getInstance();
        ------------------------------
   }
}

Thursday 6 October 2016

Publisher And Subscriber Thread example using wait, notify & sleep methods

Publisher And Subscriber Thread example using wait, notify & sleep methods


Message.java

import java.util.Date;
class Message {
 
       String message = null;
 
       Message() {
message = new Date().toString();
}
 
       public void setMessage(String msg) {
message = msg;
}

public String getMessage() {
return message;
}
}

Publisher.java
import java.util.Vector;
class Publisher extends Runnable {

  static final int SIZE = 5;
  private Vector<Message> messages = null;
 
public Publisher() {
 
 messages = new Vector<Message>();

 }

    public void run() {
        try {
            while (true) {
                putMsg();
                sleep(1000);
            }
        } catch (InterruptedException exception) {
System.out.prinln("(Thread Interrupted......");
        }
    }

    private synchronized void putMsg() throws InterruptedException {
        while (messages.size() == SIZE) {
            wait();
        }
 
        //To prepare real time message usually will call services
        messages.addElement(new Message());
        System.out.println("put msg");
        notify();
    }

    public synchronized String getMsg() throws InterruptedException {
        notify();
        while (messages.size() == 0) {
            wait();
        }
        String tempMessage = (String) messages.firstElement();
        messages.removeElement(tempMessage);
        return tempMessage;
    }
}

Subscriber.java
class Subscriber extends Runnable {

    Publisher publisher= null;

    Subscriber(Publisher p) {
        publisher = p;
    }


    public void run() {
        try {
            while (true) {
                String msg = publisher.getMsg();
                System.out.println("Consumed message........." + msg);
                sleep(500);
            }
        } catch (InterruptedException exception) {
            System.out.prinln("(Thread Interrupted......");
        }
    }
}

PublisherAndSubscriberDemo.java
public class PublisherAndSubscriberDemo {

public static void main(String args[]) {
        Thread publisherThread = new Publisher();
        publisherThread.start();
        Thread  subscriberThread = new Subscriber(publisherThread);
subscriberThread.start();
    }

}

Tuesday 4 October 2016

Questions

Executor Frame Work in Java 1.6
Strategy Design Pattern in Java
 How many interfaces required to Builder Design pattern in Java
Capabilities of Jan-kins and had-son build tools

1.how to make object unmodifable of final class while creating immutable class
2. fail safe and fail fast and how concurrent hashmap handles if one thread accessing from same bucket and another
thread is removing/adding from same bucket
3. interface1 and interface2 same set of methods; what happens if class is going to implement both the interfces.
4.
Inter i1 = new Ineteger(10);
Inter i2 = new Ineteger(10);

i1 == i2                                            false

i1.equals(i2);                                   true

i1.equals("10");                               false

"10".equals(i1);                               false

Difference between HashSet and TreeSet:

HashSet: complexity to access element is O(1), it uses hashing algorithm to store values,and it will not give any guarantee to maintain sorted order  and it allows null objects.

TreeSet: complexity to access element is O(log n), it is uses tree structure algorithm to store values, it maintains data in sorted order and it will not allow null objects.

HashSet performance is more than TreeSet.


Maven command to execute micro service:

mvn clean install -DSkipTest=true & java -jar MicroService.jar

Friday 17 October 2014

JQuery Colorbox Demo

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
  <style>
body{font:12px/1.2 Verdana, sans-serif; padding:0 10px;}
a:link, a:visited{text-decoration:none; color:#416CE5; border-bottom:1px solid #416CE5;}
h2{font-size:13px; margin:15px 0 0 0;}
</style>
<script src="js/jquery-1.8.1.js"></script>
<script src="js/jquery.colorbox.js"></script>
<link rel="stylesheet" href="js/colorbox.css" />
  <SCRIPT LANGUAGE="JavaScript">
  <!--
  $(document).ready(function () {
   jQuery('<div id="close" style="cursor: pointer; position: absolute; top: 0; right: 2px;"><img src="close.png" alt="close"/></div>').appendTo('#contentdiv');
$("#close").click(function() {
            jQuery('#cboxClose').click();
        });

$('#colrboxanchor').click(function () {
$("div#contentdiv").colorbox({
'href':'div#contentdiv',
'top':50,
'left':100,
'inline':true,
'width':400,
'height':400,
'opacity':0.3,
overlayClose:false,
'open':true,
onComplete: function() {
$(this).focus();
},
onClosed:function(){
                    $.colorbox.remove();
                }
});
});
  $('#btn').click(function () {
  alert("1111111111111");
  });
  });

    //-->
  </SCRIPT>
 </HEAD>

 <BODY>
 <div>
<div style="display:none">
<div id="contentdiv">
          <p>div content from request.<br/>welcome to colorbox<br/>It is lightweight jquery box(popup)</br></p>
</div>
</div>
<a  href="#" id="colrboxanchor">Click here to get colorbox popup</a>
<INPUT TYPE="button" id="btn" value="Click"/>
</div>
 </BODY>
</HTML>

Monday 18 August 2014

Steps to Configure Tiles in Spring & Struts2 Applications



  Steps to Configure Tiles in Spring Application
  

Step 1: Add tiles Jars to lib folder
Step 2:  Create tiles.xml file

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE tiles-definitions PUBLIC
  "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
  "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
<tiles-definitions>
    <definition name="baseLayout" template="/jsp/baselayout.jsp">
        <put name="title" value="" />
        <put name="header" value="/jsp/header.jsp" />
        <put name="leftPannel" value="/jsp/leftPannel.jsp" />
        <put name="body" value="" />
        <put name="footer" value="/jsp/footer.jsp" />
    </definition>
    <definition name="homepage" extends="baseLayout">
        <put name="title" value="Welcome" />
        <put name="body" value="/jsp/welcome.jsp" />
    </definition>
    <definition name="searchpage" extends="baseLayout">
        <put name="title" value="Welcome" />
        <put name="body" value="/jsp/searchpage.jsp" />
    </definition>
</tiles-definitions>


Step 3: Spring beans configuration

 <!-- Configures the tiles defintions file -->
    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tile/tiles-def.xml</value>
            </list>
        </property>
    </bean>

    <!-- view mappings from localized classpath files -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass">
            <value>
                org.springframework.web.servlet.view.tiles.TilesJstlView
            </value>
        </property>
    </bean>

Step 4: Create baselayout.jsp and create all required jsp pages

<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><tiles:insert name="title" ignore="true" /></title>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%" align="center">
    <tr height="15%">
        <td><tiles:insert name="header" />
        </td>
    </tr>
    <tr height="75%">
    <td>
        <TABLE border="0" cellpadding="0" cellspacing="0" width="100%" height="100%">
        <TR>
            <td height="80%" width="20%"><tiles:insert name="leftPannel" /></td>
            <td width="80%">
                <table>
                    <tr  height="100%">
                        <td>
                            <tiles:insert name="body" />
                        </td>
                    </tr>
                </table>
            </td>
        </TR>
        </TABLE>
    </td>       
    </tr>
    <tr height="10%">
        <td><tiles:insert name="footer" />
        </td>
    </tr>
</table>
</body>
</html>







Step 5: Create & Return model and view object with tiles definition in controller class

            return new ModelAndView("homepage");

Steps to Configure Tiles in Struts 2 Application

Step 1: Add tiles Jars to lib folder


Step 2: web.xml configuration

   <listener>
        <listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
    </listener>

    <context-param>
        <param-name>tilesDefinitions</param-name>
        <param-value>/WEB-INF/tiles.xml</param-value>
    </context-param>

Step 3: Struts 2 action configuration 

<package name="default" namespace="/" extends="struts-default">
<result-types>
    <result-type name="tiles"
        class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<action name="ajaxRequestForJsp">
            <result name="successtype="tiles">/ajaxRequestForJsp</result>
</action>
</package>

Step 4:  Create tiles.xml file

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE tiles-definitions PUBLIC       
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"       
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
    <definition name="baseLayout" template="/jsp/baselayout.jsp">
        <put-attribute name="title" value="" />
        <put-attribute name="header" value="/jsp/header.jsp" />
        <put-attribute name="leftPannel" value="/jsp/leftPannel.jsp" />
        <put-attribute name="contentbody" value="" />
        <put-attribute name="footer" value="/jsp/footer.jsp" />
    </definition>
    <definition name="/ajaxRequestForJsp" extends="
baseLayout">
        <put-attribute name="
contentbody" value="/jsp/ajaxJspResponse.jsp" />
    </definition>
</tiles-definitions>  


 Step 5: Create baselayout.jsp and create all required jsp pages


<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="css/ajaxdemocss.css" rel="stylesheet" type="text/css" />
<SCRIPT LANGUAGE="JavaScript" src="javascript/ajax_javascript.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript" src="javascript/jquery-1.8.1.js"></SCRIPT>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%" align="center">
    <tr height="15%">
        <td><tiles:insertAttribute name="header" />
        </td>
    </tr>
    <tr height="75%">
    <td>
        <TABLE border="0" cellpadding="0" cellspacing="0" width="100%" height="100%">
        <TR>
            <td height="80%" width="10%"><tiles:insertAttribute name="leftPannel" /></td>
            <td width="90%">
                <table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%">
                <tr height="70%"><td><tiles:insertAttribute name="contentbody" /></td></tr>
                </table>
            </td>
        </TR>
        </TABLE>
    </td>       
    </tr>
    <tr height="10%">
        <td><tiles:insertAttribute name="footer" />
        </td>
    </tr>
</table>
</body>
</html>