Wednesday, 1 June 2016

Method injection with Spring

Spring core comes out-of-the-box with two scopes: singletons and prototypes. Singletons implement the Singleton pattern, meaning there’s only a single instance at runtime (in a JVM). Spring instantiate them during context creation, caches them in the context, and serves them from the cache when needed (or something like that). Prototypes are instantiated each time you access the context to get the bean.
Problems arise when you need to inject a prototype-scoped bean in a singleton-scoped bean. Since singletons are created (and then injected) during context creation: it’s the only time the Spring context is accessed and thus prototype-scoped beans are injected only once, thus defeating their purpose.
In order to inejct prototypes into singletons, and side-by-syde with setter and constructor injection, Spring proposes another way for injection, called method injection. It works in the following way: since singletons are instantiated at context creation, it changes the way prototype-scoped are handled, from injection to created by an abstract method. The following snippet show the unsuccessful way to achieve injection:
public class Singleton {

    private Prototype prototype;

    public Singleton(Prototype prototype) {
        this.prototype = prototype;
    }

    public void doSomething() {
        prototype.foo();
    }

    public void doSomethingElse() {
        prototype.bar();
    }
}
The next snippet displays the correct code:
public abstract class Singleton {

    protected abstract Prototype createPrototype();

    public void doSomething() {
        createPrototype().foo();
    }

    public void doSomethingElse() {
        createPrototype().bar();
    }
}
As you noticed, code doesn’t specify the createPrototype() implementation. This responsibility is delegated to Spring, hence the following needed configuration:
<bean id="prototype" class="ch.frankel.blog.Prototype" scope="prototype" />
<bean id="singleton" class="sample.MySingleton">
 <lookup-method name="createPrototype" bean="prototype" />
</bean>
Note that an alternative to method injection would be to explicitly access the Spring context to get the bean yourself. It’s a bad thing to do since it completely defeats the whole Inversion of Control pattern, but it works (and is essentially the only option when a nasty bug happens on the server - see below).
However, using method injection has several main limitations:
  • Spring achieves this black magic by changing bytecode. Thus, you'll need to have the CGLIB libraryon the classpath.
  • The feature is only available by XML configuration, no annotations (see this JIRAfor more information)
  • Finally, some application servers have bugs related to CGLIB (such as this one)

tomcat 7 difference nio (non blocking I/O) vs bio (blocking I/O)

Tomcat has a couple of connectors to choose from. I’ll leave aside the APR connector, and focus on the BIO and NIO.
The BIO connector (blocking I/O) is blocking – it uses a thread pool where each thread receives a request, handles it, responds, and is returned to the pool. During blocking operations (e.g. reading from database or calling an external API) the thread is blocked.
The NIO connector (non-blocking I/O) is a bit more complicated. It uses the java NIO library and multiplexes between requests. It has two thread pools – one holds the the poller threads, which handle all incoming requests and push these requests to be handled by worker threads, held in another pool. Both pool sizes are configurable.
When to prefer NIO vs BIO depends on the use case. If you mostly have regular request-response usage, then it doesn’t matter, and even BIO might be a better choice (as seen in my previous benchmarks). If you have long-living connections, then NIO is the better choice, because it can server more concurrent users without the need to dedicate a blocked thread to each. The poller threads handle the sending of data back to the client, while the worker threads handle new requests. In other words, neither poller, nor worker threads are blocked and reserved by a single user.
With the introduction of async processing servlet it became easier to have the latter scenario from the previous paragraph. And maybe that was one of the reasons to switch the default connector from BIO to NIO in Tomcat 8. It’s an important thing to have in mind, especially because they didn’t exactly change the “default value”.
The default value is always “HTTP/1.1″, but in Tomcat 7 that “uses an auto-switching mechanism to select either a blocking Java based connector or an APR/native based connector”, while in Tomcat 8 “uses an auto-switching mechanism to select either a non blocking Java NIO based connector or an APR/native based connector”. And to make things even harder, they introduced a NIO2 connector. And to be honest, I don’t know which one of the two NIO connectors is used by default.
So even if you are experienced with tomcat configuration, have in mind this change of defaults. (And generally I’d recommend reading the documentation for all the properties and play with them on your servers)
for more detail check http://techblog.bozho.net/tomcats-default-connectors/

Monday, 30 May 2016

Difference between a Spring singleton and a Java singeleton (design pattern)

Singleton beans in Spring and classes based on Singleton design pattern are quite different.
The Java singleton is scoped by the Java class loader, the Spring singleton is scoped by the container context.
Which basically means that, in Java, you can be sure a singleton is a truly a singleton only within the context of the class loader which loaded it. Other class loaders should be capable of creating another instance of it (provided the class loaders are not in the same class loader hierarchy), despite of all your efforts in code to try to prevent it. In Spring, if you could load your singleton class in two different contexts and then again we can break the singleton concept. So, in summary, Java considers something a singleton if it cannot create more than one instance of that class within a given class loader, whereas Spring would consider something a singleton if it cannot create more than one instance of a class within a given container/context.
Here is some example:
spring-config.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 <beans xmlns="http://www.springframework.org/schema/beans"  
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
     xmlns:context="http://www.springframework.org/schema/context"  
     xsi:schemaLocation="http://www.springframework.org/schema/beans   
       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
       http://www.springframework.org/schema/context   
       http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
   <bean id="a" class="com.pkg.Singleton" scope="singleton" />    
 </beans>  
Bean Singleton
 public class Singleton{  
   private String text;  
   public String getText() {  
     return text;  
   }  
   public void setText(String text) {  
     this.text = text;  
   }  
 }  
Test 
 public class Test {  
   public static void main(String[] args) {  
     ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");  
     Singleton a1 = ctx.getBean("a", Singleton.class);  
     a1.setText("text A1");  
     Singleton a2 = ctx.getBean("a", Singleton.class);  
     a2.setText("text A2");  
     System.out.println("a1: " + a1.getText());  
     System.out.println("a2: " + a2.getText());  
   }  
 }  
Output: 
 a1: text A2  
 a2: text A2  
And now let's create another one ApplicationContext: 
 public class Test {  
   public static void main(String[] args) {  
     ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");  
     ApplicationContext ctx2 = new ClassPathXmlApplicationContext("spring-config.xml");  
     Singleton a1 = ctx.getBean("a", Singleton.class);  
     a1.setText("text A1");  
     Singleton  a2 = ctx2.getBean("a", Singleton.class);  
     a2.setText("text A2");  
     System.out.println("a1: " + a1.getText());  
     System.out.println("a2: " + a2.getText());  
     // both ctx and ctx2 have same classloaders  
     System.out.println("context1 classloader: " + ctx.getClassLoader());  
     System.out.println("context2 classloader: " + ctx2.getClassLoader());  
   }  
 }  
Output: 
 a1: text A1  
 a2: text A2  
 context1 classloader: sun.misc.Launcher$AppClassLoader@5284e9  
 context2 classloader: sun.misc.Launcher$AppClassLoader@5284e9  

Thursday, 26 May 2016

What's the difference between MyISAM and InnoDB in Mysql db

MYISAM:
  1. MYISAM supports Table-level Locking
  2. MyISAM designed for need of speed
  3. MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS
  4. MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)
  5. MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.
  6. MYISAM supports fulltext search
  7. You can use MyISAM, if the table is more static with lots of select and less update and delete.
INNODB:
  1. InnoDB supports Row-level Locking
  2. InnoDB designed for maximum performance when processing high volume of data
  3. InnoDB support foreign keys hence we call MySQL with InnoDB is RDBMS
  4. InnoDB stores its tables and indexes in a tablespace
  5. InnoDB supports transaction. You can commit and rollback with InnoDB

Sunday, 15 May 2016

session sharing in tomcat cluster environment using memcache session manager

memcached-session-manager is a tomcat session manager that keeps sessions in memcached, for highly available, scalable and fault tolerant web applications. It supports both sticky and non-sticky configurations, and is currently working with tomcat 6.x, 7.x and 8.x. For sticky sessions session failover (tomcat crash) is supported, for non-sticky sessions this is the default (a session is served by default by different tomcats for different requests). Also memcached failover (memcached crash) is supported via migration of sessions. There shall also be no single point of failure, so when a memcached fails the session will not be lost (but either be available in tomcat or in another memcached).




\
How it Works:
User u1 send request to load balancer which have configured multiple server as 
cluster.suppose request r1 goes to tomcat t1 which create a session s1 with host name
and save it memcache server.

When the next request comes from same user with session id s1 it is directed to tomcat t1 
because of stickty session and help to reduced call to memcache server.

If tomcat t1 is down due to any reason any further request will be directed to tomcat t2 but it 
does not have user session or request may fails ,what it do is it get session from memcache server
which is centeral cache store for tomcat cluster. 
<Context>
  ...
  <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
    memcachedNodes="n1:host1.yourdomain.com:11211,n2:host2.yourdomain.com:11211"
    failoverNodes="n1"
    requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$"
    transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory"
    />
</Context>
Reference
https://github.com/magro/memcached-session-manager/wiki/SetupAndConfiguration
https://github.com/magro/memcached-session-manager
Sample Server
https://github.com/magro/memcached-session-manager/tree/master/samples

Friday, 22 April 2016

filtering on li data in ul list

<div id="container">
  <input type="search" class="search form-control" placeholder="Search files and folders" id="s">
  <div class="row asset-list" id="1">
        <div class="name col-xs-8">
          <a href="/rack/c27178a4e33d83be3cd0fb955c9b1f3b7b96fa6ashow.html?1395131765" class="file-name">show.html</a>
        </div>

        <div class="size col-xs-1">
          5.9 KB
        </div>

        <!-- <div class="col-xs-2">
          text/html
        </div> -->

        <div class="col-xs-3">
          <time data-local="time-ago" datetime="2014-03-18T08:36:05Z">March 18, 2014  8:36am</time>
          <div class="actions pull-right">
            <div class="share">
                <a href="/home/index">Share</a>
            </div>
           
          </div>
        </div>
</div>
<hr />
<div class="row asset-list" id="2">
        <div class="name col-xs-8">
          <a href="/rack/4f1032b2181be5f52f2585adf9705c750cd6683enext-prev-btn.png?1395080071" class="file-name">next-prev-btn.png</a>
        </div>

        <div class="size col-xs-1">
          1.5 KB
        </div>

        <!-- <div class="col-xs-2">
          image/png
        </div> -->

        <div class="col-xs-3">
          <time data-local="time-ago" datetime="2014-03-17T18:14:31Z">March 17, 2014  6:14pm</time>
          <div class="actions pull-right">
            <div class="share">
                <a href="/home/index">Share</a>
            </div>
           
          </div>
        </div>
</div>
<hr />
<div class="row asset-list" id="3">
        <div class="name col-xs-8">
          <a href="/rack/ec9dfae49b3bce8c58da7091337c25c0795649a4apple_mac_os_x_mavericks-wallpaper-1024x768.jpg?1394374377" class="file-name">apple_mac_os_x_mavericks-wallpaper-1024x768.jpg</a>
        </div>

        <div class="size col-xs-1">
          270 KB
        </div>

        <!-- <div class="col-xs-2">
          image/jpeg
        </div> -->

        <div class="col-xs-3">
          <time data-local="time-ago" datetime="2014-03-09T14:12:57Z">March  9, 2014  2:12pm</time>
          <div class="actions pull-right">
            <div class="share">
                <a href="/home/index">Share</a>
            </div>
           
          </div>
        </div>
</div>
<hr />
<div class="row asset-list" id="4">
        <div class="name col-xs-8">
          <a href="/rack/3407111f96921ff5f1bd868007b26940367ae3f1Book1_(Autosaved).xlsx?1394298133" class="file-name">Book1_(Autosaved).xlsx</a>
        </div>

        <div class="size col-xs-1">
          11 KB
        </div>

        <!-- <div class="col-xs-2">
          application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
        </div> -->

        <div class="col-xs-3">
          <time data-local="time-ago" datetime="2014-03-08T17:02:13Z">March  8, 2014  5:02pm</time>
          <div class="actions pull-right">
            <div class="share">
                <a href="/home/index">Share</a>
            </div>
           
          </div>
        </div>
</div>
</div>

for more details check http://jsfiddle.net/rb7hm/4/

Thursday, 21 April 2016

Enabling https on node js using proxy

App.js

var https = require('https');

var fs = require('fs');


 var options = {
 key: fs.readFileSync('/etc/apache2/ssl/apache.key'),
 cert: fs.readFileSync('/etc/apache2/ssl/apache.crt')
};

// Create an HTTPS service identical to the HTTP service.
https.createServer(options,app).listen(5000);


Configuration in /etc/apache2/sites-available/default-ssl.conf

On Ubuntu or debain

SSLProxyEngine On
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off

ProxyPass /naf/node/ https://localhost:5000/naf/node/

On RedHat 

       SSLProxyEngine On
        SSLProxyVerify none
        SSLProxyCheckPeerCN off
        SSLProxyCheckPeerExpire off

        ProxyPreserveHost On
        <Proxy balancer://nodecluster>
        BalancerMember https://172.16.84.96:5000
        </Proxy>
        ProxyPass /naf/inbox balancer://nodecluster/naf/inbox