Wednesday 21 December 2016

Null/Equality/Empty Check in String

 If you are checking two references  for equality/empty:

Make sure that null check must appear first and then invoke equals () on String to avoid NullPointerException.

If (str == null && str.equals(str1))


If you are checking constant literal against string then make sure literal should be on the left side in order to avoid additional null check :

If (CONSTANT_VALUE.equals(str))


CONSTANT_VALUE is a final variable and must initialized with some value so we can skip null check for the str variable.

If you are checking null or empty then make sure that the following syntax :

if(str1!= null && !(str1.isEmpty()))

Thursday 8 December 2016

Embeeded vs Reference approach in MongoDB

In General, there are 2 ways to maintain a relation between entities in Mongo :

1. Embedded approach (Strong association- By default) : The document will be persisted in the same collection. Read operation will result better performance as compared to Relational database as we don't require join operation at all but this approach should be avoid in case of

⦁    weak association
⦁    More data growth- i.e.  when the document fields has more chances of growth  i.e. frequent insert operations such as pushing elements to an array or adding new fields.
⦁    In Many to Many association



However Put as much in as possible by considering the document size .MongoDB imposes a 4MB (16MB with 1.8) size limit on a single document.In general  any data that is not useful apart from its parent document should be part of the same document.
The another good news is that we can lazily load the data also.


However one more disadvantage of embedded approach is that An unique ID (_id) is not set on nested subdocuments by default it is only only on root docuemnts.

MongoDB CRUD operations (insert, update, find, remove) all operate on top-level documents exclusively -- although of course you can filter by fields in embedded documents. Embedded documents are always returned within the parent document.

The _id field is a required field of the parent document, and is typically not necessary or present in embedded documents. If you require a unique identifier, you can certainly create them, and you may use the _id field to store them if that is convenient for your code or your mental model; more typically, they are named after what they represent (e.g. "username", "otherSystemKey", etc). Neither MongoDB itself, nor any of the drivers will automatically populate an _id field except on the top-level document.

Specifically in Java, if you wish to generate ObjectId values for the _id field in embedded documents, you can do so with:

someEmbeddedDoc._id = new ObjectId();


Therefore while performing any CRUD operation we have to explicitly take care of generating the unique id for all the subdocuments.

http://stackoverflow.com/questions/11255100/mongodb-embedded-objects-have-no-id-null-value/11263912#11263912



Therefore it is better to implement embedded approach for 1 : 1 relationship or 1: M relationship only when M value is not so large.





2. Reference approach  (Weak association) : Using @DBRef annotation that persist the referenced class in a separate collection therefore Separate data that can be referred to from multiple places into its own collection. If many records will refer to the same data it is more efficient and less error prone to update a single record and keep references to it in other places. The use of DBRef require an extra query for read operation and hence affect performance.




Why we shouldn't use Embedded approach in case of data growth :
Let say a collection has an association with a 1000 of document.

Consider an example -  Let say a User collection has strong association with posts document and posts document itself has strong association with comments. Now If there are 1000 comments per post, and the user commented on 3 posts, you’ll have to wade through 3000 comments to get a specific comment matched with your query (word or phrase).There’s no way to get only the matched comment back.

Reason  :  It is impossible to return a subset of elements in a document. If you need to pick-and-choose a few bits of each document, it will be easier to separate them out.



Summary :

As a general rule, if you have a lot of "documents" in a collection or if they are large, a separate collection might be best.

Smaller and/or fewer documents tend to be a natural fit for embedding.


So we need to focus on the entities  that contain too many relationship with other entity so we will keep only the reference of child entity in parent and if we know let say merchant has only few location then it would be better to make it embedded.

However while designing the model schema & business need, we must keep all these factors in mind.


However I am pretty sure about the above behavior but not sure which entities has more chances of growth in future according to the business needs? It would help us to make best use of MONGO and better comparison with SQL.
Please suggest and advice.

Friday 2 December 2016

Difference between Interceptor and Filter

A HandlerInterceptor gives you more fine-grained control than a filter, because you have access to the actual target "handler" - this means that whatever action you perform can vary depending on what the request is actually doing (whereas the servlet filter is generically applied to all requests - only able to take into account the parameters of each request). The handlerInterceptor also provides 3 different methods, so that you can apply behavior prior to calling a handler, after the handler has completed but prior to view rendering (where you may even bypass view rendering altogether), or after the view itself has been rendered. Also, you can set up different interceptors for different groups of handlers - the interceptors are configured on the handlerMapping, and there may be multiple handlerMappings.

Therefore, if you have a need to do something completely generic (e.g. log all requests), then a filter is sufficient - but if the behavior depends on the target handler or you want to do something between the request handling and view rendering (for ex-to redirect to some other handler object or URL), then the HandlerInterceptor provides that flexibility.

Hope this gives you a general idea. You can also read more here: http://static.springframework.org/sp...ng-interceptor !

Can I get HttpServletRequest instance during application startup

When the application is starting there are no HTTP servlet requests yet. In fact, Tomcat during bootup starts listening and accepting connections on 8080 port, but passes them to appropriate servlets only when all applications have successfully started. This means you cannot call yourself during startup since this will lead to deadlock - you are waiting for a response which is blocked by Tomcat that waits for you.
This also means that it is simply impossible (at least when Tomcat is taken as an exmaple) to obtain any HTTP servlet request during startup as there are absolutely no requests yet. Yes, mocking is the correct way, but I'm afraid if these libraries require an HttpServletRequest instance, simple mock might not be enough.

Reference : http://stackoverflow.com/questions/9130390/how-to-generate-an-httpservletrequest-during-spring-startup-for-a-bean-initialis

Monday 3 October 2016

Understanding static for Database interaction and when we should use static

This is very common practice when a developer thinks whether a method should be static or not during development and generally an average developer always use static for Utility data but when it comes to Database call, most of developers confuse when should we use static ????




Understanding of Static

Why we declare static ??

Ans : Those method which consist the data which is common for multiple objects, never changes or infrequent changes.

Q. When static method and when static block gets initialize the data ?
Ans : static method gets initialize the data when we invoke it.Static block initialize the data during class loading time.

static blocks invoked and gets initialize the data after a first call of the mehod and their state never changes after that during program execution.

This is the reason that the data which actually changes shouldn't be accessed through static block. Therefore static blocks used in caching.

For ex- If a static block invoked already and fetch some data from Database and now accessing the data from static block will return same data which actually we got on first call. Therefore if a UI which contains data from DB will result stale data.


So now the next question is :

Q. So we shouldn't use static block for Database interaction ?
Ans : Generally we shouldn't use for database interaction but in some special cases for ex- In caching, we can use static methods to gets stale data from cache and after certain amount of time (caching refresh interval) we can have static method call.

Or the data which never changes in the database can be accessed via static block.

Similarly the Connection to a Database itself never changes annd therefore we can access it via static block or method..


Q. What is the difference between static block and static method ?

Ans : Static block initialize the data during class loading in which the block declared but static method gets initialized the data only when we called the method.

Q. Can't we use static block for read only data ?
Ans : First we need to understand the difference between Read only data and data never changes. Read only data is the data which a particular user or entity has not permisssion. Data never changes is the data which never changes throughout its life. For ex- Age of a person - we can declare static because it never changes throughout the object life cycle and similarly historical data.

Thefore static has no relation with read only data but it can be used to access infrequent or never changing data.


Q. When should use static block ?
Ans : When we need data during application initialization, caching purpose etc

Q. When should we use static method ?
Ans : Define static methods in the following scenarios only:
  1. If you are writing utility classes and they are not supposed to be changed.
  2. If the method is not using any instance variable.
  3. If any operation is not dependent on instance creation.
  4. If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
  5. If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
In general : One rule-of-thumb: ask yourself "does it make sense to call this method, even if no Obj has been constructed yet?" If so, it should definitely be static.
So in a class Car you might have a method double convertMpgToKpl(double mpg) which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. But void setMileage(double mpg) (which sets the efficiency of one particular Car) can't be static since it's inconceivable to call the method before any Car has been constructed.
(Btw, the converse isn't always true: you might sometimes have a method which involves two Carobjects, and still want it to be static. E.g. Car theMoreEfficientOf( Car c1, Car c2 ). Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which Car is more important, you shouldn't force a caller to choose one Car as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.)

Q. Then why we use static method for utility classes ?
Ans : A utility class is one whose behaviour never changes and remain same irrespective of the application state.

Q. Can we use static method for Database call ?

Ans : Yes but if we really need it .For ex- if two or more objects sharing a data accessed from Database then in that case we can access the data through static method.

Q. Why in MVC - service classes shouldn't contain static method if multiple controller classes may need the same method and generally request routing through the controller return stateless data ?
Ans : Straight reason : It violate the service spec because we cant put the service method in in the service interface.

but why we generally dont need because of the following reasons :

(I) you can't replace Service with a mock easily during tests (tools like PowerMock aside)
(ii) static methods do not participate in standard, proxy-based AOP (no transactions, security, custom aspects)
(iii) you can no longer use fancy injection techniques, like injecting HTTP request (request scoped) into singleton scoped services (poor design anyway, but...)
But to be complete, there are also advantages:

static method is actually closer to your intent, Spring beans are very rarely stateful, thus they don't really need an instance to work
static call might be faster


Q. In Transaction which one should use ?
Ans : no one transaction data never access in static...i.e. why I said static always for caching and never for transaction in application infrastructure.


Thursday 28 July 2016

How to enable a port in Linux

Go to /etc/sysconfig/ and open iptables-config file

add following entries :
iptables -A INPUT -p tcp --dport 3306 -j ACCEPT

iptables -A OUTPUT -p tcp --dport 3306 -j ACCEPT

save and close the file

Finally type the following command :
iptables-save

Verify whether port is enabled or not by using following command :

 netstat -lnt | awk '$6 == "LISTEN" && $4 ~ ".3306"'